I have a table that uses a custom_primary_key as an id which is a combination of 4 fields in the current table. I created a pre_save signal to concatenate the 4 fields to use it as an id. It is working fine with the save() and create() methods but I also wanted to implement the same logic with the bulk_create() method, how can I send each item in bulk_create to use the pre_save signal that generates the primary key value?
This is a sample code of what I'm trying to achieve but it seems that it is not reading the signals from the bulk_create method.
The error says: django.db.utils.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, 1, 2, 3, 4).
class CustomManager(models.Manager):
def bulk_create(self, objs, **kwargs):
for obj in objs:
pre_save.send(obj.__class__, instance=obj)
return super().bulk_create(objs, **kwargs)
class MyModel(models.Model):
objects = CustomManager()
id = models.BigIntegerField(primary_key=True)
field1 = models.IntegerField()
field2 = models.IntegerField()
field3 = models.IntegerField()
field4 = models.IntegerField()
def generate_custom_id(sender, instance, **kwargs):
instance.id = {}{}{}{}.format(instance.field1, instance.field2, instance.field3, instance.field4)
pre_save.connect(generate_custom_id, sender=MyModel)