Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django bulk_create function example

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
    ),
})
like image 786
GrantU Avatar asked Aug 22 '13 14:08

GrantU


People also ask

What is Bulk_create in Django?

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.

What is bulk create?

Bulk create lets you construct multiple data sources, derived signals, segments, traits, and other items with a single operation.


2 Answers

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)
like image 175
falsetru Avatar answered Oct 02 '22 02:10

falsetru


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'),
 ])
like image 29
Dinokor Avatar answered Oct 04 '22 02:10

Dinokor