Created
July 10, 2019 04:19
-
-
Save repodevs/f3fde0cd1da0b587e63fd0c328f698a6 to your computer and use it in GitHub Desktop.
Django multiple insert data / bulk create
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @repodevs!!
Line 18 helps me!