Reputation: 81
This is with Python 3.8
and Django 3.1.3
I have a model with an unique field
class SomeModel(models.Model):
name = models.CharField(max_length=200, unique=True)
I'm searching a way to automatically change the field value if there is an UNIQUE constraint violation.
If I create a new instance with name="Kevin"
while another instance already exists with the same, it would change the name of the new instance with a suffix when save() is called.
eg : database is empty
>>> foo = SomeModel()
>>> foo.name = "kevin"
>>> foo.save()
# again
>>> foo = SomeModel()
>>> foo.name = "kevin"
>>> foo.save()
# and again
>>> foo = SomeModel()
>>> foo.name = "kevin"
>>> foo.save()
>>> for foo in SomeModel.objects.all():
>>> print(foo.name)
kevin
kevin_01
kevin_02
Didn't found the way to do this, I suppose I have to override the save method and catch the unique constraint error to do that. any ideas ? Thanks
Upvotes: 5
Views: 7370
Reputation: 159
Model instances that violate the UNIQUE constraint will throw an IntegrityError if an entry in the database already has the same value, so the traditional way to handle this would be in a custom save method on the model using a try/except block.
from django.db import IntegrityError
class SomeModel(models.Model):
name = models.CharField(max_length=200, unique=True)
def save(self, *args, **kwargs):
try:
self.name = 'kevin'
super(SomeModel, self).save(*args, **kwargs)
doSomething()
except IntegrityError:
doSomethingElse()
Upvotes: 6