36👍
bulk_create
takes a list of objects as a single arg, in a single call. What you are doing in your example would be the same as looping and doing create()
Referencing: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create
aList = [
Entry(headline="Django 1.0 Released"),
Entry(headline="Django 1.1 Announced"),
Entry(headline="Breaking: Django is awesome")
]
Entry.objects.bulk_create(aList)
aList
refers to a list of objects that you already have instantiated and need to create in bulk with one query. If for instance you didn’t already have that list of unsaved instances, and you had a list of values, you could then create your list with something like:
values = ['abc', 'def', 'ghi']
# a list of unsaved Entry model instances
aList = [Entry(headline=val) for val in values]
Or maybe you have a list of raw dictionary values that map to the model:
values = [{headline="abc"}, {headline="def"}, {headline="ghi"}]
aList = [Entry(**vals) for vals in values]
5👍
>>> Entry.objects.bulk_create([
... Entry(headline="Django 1.0 Released"),
... Entry(headline="Django 1.1 Announced"),
... Entry(headline="Breaking: Django is awesome")
... ])
You’re passing the ORM a list of instantiated objects in a list. Using this, and supposing that orig_list is a list of dictionaries,
>>> my_objects = [MyObject(a=x['a'], b=x['b']) for x in orig_list]
>>> MyObject.objects.bulk_create(my_objects)
- In a schemamigration, what should be the default value for a null=False field which I'm sure that won't have null values?
- Django Check and set permissions for a user group
- How to get all objects by instance in django
1👍
Try this, and the point of bulk_create is to hit database only once, no matter how many you are creating. That’s why we consider it to be efficient.
class Entry(models.Model):
name = models.CharField(max_length = 10)
a = ['test1', 'test2', 'test3', 'test4']
Entry.objects.bulk_create([Entry(name=x) for x in a])
—Edit—
Say you have a Model like this, in your models.py:
class Entry(models.Model):
id = models.CharField(max_length = 10)
And you have a list like this (directly copied from your question):
list = ['abc', 'def', 'ghi']
Simply one line:
Entry.objects.bulk_create([Entry(id=x) for x in list])
- Changing password in Django Admin
- Django media url is not resolved in 500 internal server error template
- Django – check cookies's "SameSite" attribute
- Can't git-push to heroku due to "Build stream timed out"