Skip to content

Instantly share code, notes, and snippets.

@repodevs
Created July 10, 2019 04:19
Show Gist options
  • Save repodevs/f3fde0cd1da0b587e63fd0c328f698a6 to your computer and use it in GitHub Desktop.
Save repodevs/f3fde0cd1da0b587e63fd0c328f698a6 to your computer and use it in GitHub Desktop.
Django multiple insert data / bulk create
"""
This is simple snippet to insert multiple data / bulk create in django
"""
# take example, we have a list of dict data
datas = [{
"name": "A",
"number: 1,
}, {
"name": "B",
"number": 2,
}, {
"name": "C",
"number": 3
}]
# make it as Django objects list
django_list = [MyModel(**vals) for vals in datas]
# Bulk Create / Insert data to database
MyModel.objects.bulk_create(django_list)
# NOTE: Using this method, the data is inserted in a single query.
# but would not calling method `save()`,
# it's mean, if you have custom `save()` method this is not good for you
# ------------
# insert multiple data with insert it one by one (I know this is not good way)
for data in django_list:
data.save()
# This method is iterate the django list and save it to db one by one by calling method `save()`
# so if you have custom method `save()` this is will work for you!.
# if you have better way to bulk/multiple insert data that also can calling `save()` method, please leave a comment :)
@uhmiller
Copy link

Thanks @repodevs!!
Line 18 helps me!

@iamkhaya
Copy link

iamkhaya commented Jul 27, 2023

There is a missing " on line 8.

@AdrianKoc84
Copy link

Thanks @repodevs!! Line 18 helps me!

For me the same.
Thanks mate!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment