Home > Blockchain >  Django bulk_create not setting the field with choices
Django bulk_create not setting the field with choices

Time:03-25

In my model.py file, I have basic and premium coupon like below.

coupon_types = (
    ("Basic", "basic"),
    ("Premium", "premium"),
)


class Coupon(Stamp):
    ...
    type = models.CharField(choices=coupon_types, max_length=256, default=coupon_types[0], null=True, blank=True)

In the code below, I am trying to create the coupon objects in the database

class ClassName:
    ...
    # Some attributes and methods
    ...
    def __construct_initiator_object(self, **kwargs):
        objs = [
            self.initiator(
                ...
                ...
                type=coupon_types[0] if self.coupon_type.lower() == 'basic' else coupon_types[1]
            )
            for code in self.coupons
        ]
        return objs

    @transaction.atomic
    def __create__(self):
        objs = self.__construct_initiator_object()
        create_objs = Coupon.objects.bulk_create(objs)

        return create_objs

My problem now is that whenever I call the create method, the bulk_create sets every other field but not the type field. I don't know if it's because I have the choices=coupon_types in the type field. Any help on how to overcome this?

CodePudding user response:

I think first you need to change your choices to something like:

class Coupon:
    BASIC = "Basic"
    PREMIUM = "Premium"
    coupon_types = (
        (BASIC, "basic"),
        (PREMIUM, "premium"),
        )
    ...
    type = models.CharField(choices=coupon_types, max_length=256, default=BASIC)

Also note that I removed null and blank from this field because you provided default value for this field and you don't need them. Please make sure your database is up to date by running makemigrations and migrate commands.

and then change your __construct_initiator_object to:

def __construct_initiator_object(self, **kwargs):
    objs = [
        self.initiator(
            ...
            ...
            type=Coupon.BASIC if self.coupon_type.lower() == 'basic' else Coupon.PREMIUM
        )
        for code in self.coupons
    ]
    return objs

And since I couldn't find your initiator method, please make sure that you are adding everything (i.e. type) to objects in that method. Hope this solves your problem.

  • Related