Syntax
field_name = models.Field (unique = True)
Django Inline Field Validation unique = True
Explanation
Illustrate uniqueness using an example. Consider a project named pythonengineering
that has an application named geeks
.
Refer to the following articles to check how to create a project and an app in Django.
Enter the following code into the models.py
file of the geeks application. We’ll use CharField to experiment with all the margin variations.
|
After running the make migrations and migrations to Django and rendering the above model, let’s create an instance from the Django admin with the string " a ". Now, to show the constraint unique = True , let’s try to create another instance of the model using the same string. Now it will show this error.
Advanced concepts with unique
This is enforced at the database level and model validation. If you try to save a model with a duplicate value in a unique field, the method save () of the model will raise django.db.IntegrityError. This parameter is valid for all field types except ManyToManyField and OneToOneField.
Note that when unique is set to True, you do not need to specify db_index because unique implies creating an index.