I'm trying to understand bulk_create in Django
This was my original query I'm trying to convert:
for e in q:
msg = Message.objects.create(
recipient_number=e.mobile,
content=batch.content,
sender=e.contact_owner,
billee=batch.user,
sender_name=batch.sender_name
)
Does that mean doing the following (below) will loop and create all the entries first then hit the database? Is this right?
msg = Message.objects.bulk_create({
Message (
recipient_number=e.mobile,
content=batch.content,
sender=e.contact_owner,
billee=batch.user,
sender_name=batch.sender_name
),
})
bulk_create() From Django doc: This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are): So instead of inserting data into db one by one in an inefficient manner it is better to use this method.
Bulk create lets you construct multiple data sources, derived signals, segments, traits, and other items with a single operation.
The second code in the question create a single object, because it pass a set with a Message object.
To create multiple objects, pass multiple Message objects to bulk_create. For example:
objs = [
Message(
recipient_number=e.mobile,
content=batch.content,
sender=e.contact_owner,
billee=batch.user,
sender_name=batch.sender_name
)
for e in q
]
msg = Message.objects.bulk_create(objs)
The Official Example:
class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
Now, to Bulk Create
Entry.objects.bulk_create([
Entry(headline='This is a test'),
Entry(headline='This is only a test'),
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With