Reputation: 3058
I have the following class:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=200)
age = models.CharField(max_length=200)
and I make two identical instances of this class:
alex_1 = Person(name='Alex', age=30)
alex_1.save()
alex_2 = Person(name='Alex', age=30)
alex_2.save()
This will save 2 entries in the person database. Is there any way to prevent the second instance (alex_2
) from being saved as it's technically a duplicate? i.e., can you implement the __eq__
and __hash__
functions for models.Model
instances?
Upvotes: 4
Views: 55
Reputation: 477854
As of django-2.2, you can use a UniqueConstraint
[Django-doc] over a combination of the fields:
from django.db.models.constraints import UniqueConstraint
class Person(models.Model):
name = models.CharField(max_length=200)
age = models.CharField(max_length=200)
class Meta:
constraints = [
UniqueConstraint(fields=['name', 'age'], name='person_unique')
]
This thus means that the combination of name
and age
values should be unique. So Person(name='Alex', age=30)
and Person(name='Alex', age=40)
will not raise an error, but two objects Person(name='Alex', age=30)
and Person(name='Alex', age=30)
will result in an error, like:
django.db.utils.IntegrityError: (1062, "Duplicate entry 'Alex-30' for key 'person_unique'")
Before django-2.2, you can use unique_together
[Django-doc]:
class Person(models.Model):
name = models.CharField(max_length=200)
age = models.CharField(max_length=200)
class Meta:
unique_together = ['name', 'age']
Upvotes: 6