1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 |
# 用for循环挨个创建,共花费37秒 for i in range ( 10000 ): name = "String number %s" % i Record.objects.create(name = name) # 用django事务只提交一次,共花费2.65秒 @transaction .commit_manually def manual_transaction(): for i in range ( 10000 ): name = "String number %s" % i Record.objects.create(name = name) transaction.commit() # 用bulk_create创建,共花费0.47秒 def builtin(): insert_list = [] for i in range ( 10000 ): name = "String number %s" % i insert_list.append(Record(name = name)) Record.objects.bulk_create(insert_list) # 用for循环挨个更新,共花费72秒: def auto_transaction(): for record inRecord.objects. all (): record.name = "String without number" record.save() # 用django事务只提交一次,共花费17秒 @transaction .commit_manually def manual_transaction(): for record inRecord.objects. all (): record.name = "String without number" record.save() transaction.commit() # 用update更新,共花费0.33秒 def builtin(): Record.objects. all ().update(name = "String without number" ) |
1
2
3
4
5
6
7
8
9
10
11
12
13 |
from django.db import models from datetime import datetime class User(models.Model): id = models.BigAutoField( '主键' , primary_key = True ) name = models.CharField( '名字' , max_length = 20 , db_index = True , default = '') create_time_one = models.DateTimeField( '创建时间' , default = datetime.now()) update_time_one = models.DateTimeField( '更新时间' , default = datetime.now) create_time_tow = models.DateTimeField( '创建时间' , auto_now_add = True ) update_time_tow = models.DateTimeField( '更新时间' , auto_now = True ) |
1
2
3
4
5 |
names = [ '张三' , '李四' ] for name in names: user = User(name = name) user.save() print (user. id ) # 此时user对象有id的值 |
1
2
3
4 |
names = [ '张三' , '李四' ] users = [User(name = name) for name in names] users = User.objects.bulk_create(users) print ([user. id for user in users]) # 此时user对象没有id的值 |
1
2
3
4
5
6
7
8 |
from django.db import models from datetime import datetime class User(models.Model): id = models.BigAutoField( '主键' , primary_key = True ) name = models.CharField( '名字' , max_length = 20 , db_index = True , blank = False , default = '') create_time = models.DateTimeField( '创建时间' , auto_now_add = True ) update_time = models.DateTimeField( '更新时间' , default = datetime.now) |
1
2
3
4
5
6
7
8
9 |
# 方法一 names = [ '张三' , '李四' ] users = [User(name = name) for name in names] users = User.objects.bulk_create(users) # 方法二 names = [ '张三' , '李四' ] users = [User(name = name) for name in names] [user.save() for user in users] |
1
2
3
4
5
6
7
8
9
10 |
# 方法一 names = [ '张三' , '李四' ] User.objects. filter (name__in = names).update(name = 'changed' , update_time = datetime.now()) # 这里必须显式对update_time赋值 # 方法二 names = [ '张三' , '李四' ] users = User.objects. filter (name__in = names) for use in users: user.name = 'changed' user.save() # 这里会自动更新update_time,但是多次save效率低 |