I have a primary key ID CharField in my model Image
, I want to create unique IDs for newly created objects. I try to achieve this by overriding the model's save method:
def save(self, *args, **kwargs):
if not self.pk: # is created
self.id = uuid.uuid4().hex
while Image.objects.filter(id=self.id).exists():
self.id = uuid.uuid4().hex
return super().save(*args,**kwargs)
The problem is, save()
doesn't seem to be called when I create objects with Image.objects.create()
, it is only called when I create the object with image=Image(...)
and then call image.save()
. As a result, the newly created object has no id assigned unless specified, which causes PostgreSQL to throw a non_unique primary key
error.
How can I make sure that unique IDs are created upon calling Image.objects.create()
?
Django version: 1.11.3
UPDATE: I realized that the overridden save() method was not called either. Turns out the problem was I was calling model's save
method in a migration. As it is pointed out in this post custom model methods are not available in migrations. I will have to copy the model's save method to the migration file.