[Django]-Django bulk_create function example

63👍

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)

2👍

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'),
 ])

0👍

name = request.data.get('name')
period = request.data.get('period')
email = request.data.get('email')
prefix = request.data.get('prefix')
bulk_number = int(request.data.get('bulk_number'))

bulk_list = list()
for _ in range(bulk_number):
    code = code_prefix + uuid.uuid4().hex.upper()
    bulk_list.append(
        DjangoModel(name=name, code=code, period=period, user=email))

bulk_msj = DjangoModel.objects.bulk_create(bulk_list)

Leave a comment