1# took 0.47 seconds
2def builtin():
3 insert_list = []
4 for i in range(10000):
5 name="String number %s" %i
6 insert_list.append(Record(name=name))
7 Record.objects.bulk_create(insert_list)
8
1bulk_create(objs, batch_size = None, ignore_conflicts = False)
2
3#eg
4Entry.objects.bulk_create([
5... Entry(headline='This is a test'),
6... Entry(headline='This is only a test'),
7... ])
8# inserts in one query (usually), caveats below:
9# doesn't signal pre_save and post_save
10# cant use child models
11# no many-to-many
12# obj list fully evaluates if objs is a generator
1objs = []
2for person in p:
3 obj = People.objects.get(email=person['email'])
4 obj.birthday = person['birthday']
5 objs.append(obj)
6People.objects.bulk_update(objs, ['birthday'], batch_size=1000)
1objs = [
2 Entry.objects.create(headline='Entry 1'),
3 Entry.objects.create(headline='Entry 2'),
4]
5objs[0].headline = 'This is entry 1'
6objs[1].headline = 'This is entry 2'
7Entry.objects.bulk_update(objs, ['headline'])
8
9# Caveats #
10# -You cannot update the model’s primary key.
11#
12# -Each model’s save() method isn’t called, and the pre_save and post_save signals aren’t
13# sent.
14#
15# -If updating a large number of columns in a large number of rows, the SQL
16# generated can be very large. Avoid this by specifying a suitable batch_size.
17#
18# - Updating fields defined on multi-table inheritance ancestors will incur an extra query per ancestor.
19# If objs contains duplicates, only the first one is updated.
20
1Entry.objects.bulk_create([
2 Entry(headline = "foo"),
3 Entry(headline = "bar")
4])