How to Create Multiple Model Objects in Django

I have a model called coupon with a foreign realation to Course model. I need to create multiple coupons with coupon model. Let's say if the count is 50 then it should save 50 coupons in the database. Can I achieve that using bulk_create() method and how to do that. Also I'm using Django Rest Framework

class Coupon(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True)
    expire_date = models.DateTimeField(verbose_name="expire_date", default=now())

Thank you!

Upvotes: 1

Views: 131

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477804

Yes, you can make use of .bulk_create(…) [Django-doc], although you first should fix the default=… parameter for the expre_date. If you set this as default=now() it will take as expire_date the time when the class was interpreted, so that is very close to when you started the server. You probably want to set this to the datetime when the coupon was created:

class Coupon(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True)
    expire_date = models.DateTimeField(verbose_name='expire_date', default=now)

You can create a number of records for a given Course with a given expire date with:

from datetime import datetime

course = None  # … ← the course for which the coupons are used
expire_date = datetime(2021, 11, 7)  # ← when will the coupons expire
n = 50  # ← number of coupons to create

Coupon.objects.bulk_create(
    [
        Coupon(course=course, expire_date=expire_date)
        for __ in range(n)
    ]
)

We thus will make one query to the database to insert all 50 coupons.

Upvotes: 2

Related Questions