How to use 'bulk create django' in Python

Every line of 'bulk create django' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
58def test_bulk_create_alt(self):
59 """Test bulk create on an alternate database"""
60 # bulk_create an alternate
61 objs = Account.objects.bulk_create([Account(name='sf_test account 4') for x in range(2)])
62 self.assertEqual(len(objs), 2)
63 test_account_qs = Account.objects.filter(name='sf_test account 4')
64 self.assertEqual(test_account_qs.count(), 2)
65 test_account_qs.delete()
66 self.assertEqual(test_account_qs.count(), 0)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

5def bulk_insert(object_list, show_sql = False):
6 """
7 Generate the sql code for bulk insertion
8 @param object_list: Django model objects
9 """
10 if not len(object_list):
11 return
12 Model = type(object_list[0])
13 table_name = Model._meta.db_table
14 fields_names = [ f.attname for f in Model._meta.fields if f.name != "id" ]
15 sql = "insert into " + table_name + ' (' + ','.join(fields_names) + ') values \n'
16 defaults = dict([(f.attname, f.default if f.default is not NOT_PROVIDED else "NULL") for f in Model._meta.fields])
17 auto_now_add = [f.attname for f in Model._meta.fields if getattr(f, "auto_now_add", False)]
18
19 def get_values(ob, fields):
20 ret = []
21 for field in fields:
22 val = getattr(ob, field)
23 if val is None:
24 val = defaults[field]
25 if field in auto_now_add:
26 val = date.today().strftime("%Y-%m-%d")
27 ret.append(str(val))
28 return ret
29
30 lines = []
31 for ob in object_list:
32 line = '("' + '","'.join(get_values(ob, fields_names)) + '")'
33 line = line.replace('"NULL"', 'NULL')
34 line = line.replace('"False"', 'False')
35 line = line.replace('"True"', 'False')
36 lines.append(line)
37 sql += ',\n'.join(lines) + ";"
38# genesfile = open('sqlgenes', 'w')
39 if show_sql:
40 print(sql)
41 return
42 cursor = connection.cursor()
43# genesfile.writelines(sql)
44 cursor.execute(sql)
45
46 transaction.commit_unless_managed()

Related snippets