In Django models, the unique
parameter is a boolean attribute that can be added to fields to enforce uniqueness constraint on the values stored in that field. When a field is marked as unique=True
, it ensures that no two records in the database can have the same value in that field. If a duplicate value is attempted to be saved, Django will raise a django.db.IntegrityError
during database operations, preventing the duplicate entry.
Lets add 2 fields inside the person class for a demo :
email = models.EmailField(unique=True, null=True)
username = models.CharField(max_length=30,unique=True, null=True)
You need to run python manage.py makemigrations
and python manage.py migrate
to add the fields inside the model.
python manage.py makemigrations
python manage.py migrate
Now the fields are added and you can assign value for them.
from modeldemo.models import Person
p=Person.objects.get(id=1)
vars(p)
p.email="test@edkool.com"
p.username="edkool"
p.save()
vars(p)
Now, if you try to assign the same values to some other row, it will show an error.
p=Person.objects.create(first_name='Test',last_name='Demo', birth_date='1996-01-01', username='edkool')
The error would be like :
sqlite3.IntegrityError: UNIQUE constraint failed: modeldemo_person.username
The same error would occur, even if the email field gets a duplicate value.
p=Person.objects.create(first_name='Test',last_name='Demo', birth_date='1996-01-01', email='test@edkool.com')
The error would look like :
sqlite3.IntegrityError: UNIQUE constraint failed: modeldemo_person.email