Django Model Manage UNIQUE constraint error in save method

Viewed 3127

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 name ="kevin", 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 find 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

1 Answers

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()
Related