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.
idfield to havedefault=uuid.uuid4(no parentheses after theuuid4) and this will happen automatically on object creation.To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database.so please clarify why you think so?pknameid?To create and save an object in a single step, use the create() method.so I would expect this usingcreate()cause a problem. Besides, code base is big and there are different ways that create objects (e.g.get_or_create()). I don't want to go through the whole code base and hunt down these methods to see whether they usecreate()orsave().