Reputation: 41
Is there a directive in models.py that allows me to have a value not repeated in a field? I'm making a table of people and I need the email field not to be repeated.
Upvotes: 1
Views: 118
Reputation: 476624
Yes, you can pass unique=True
[Django-doc] to that field.
For example:
from django.db import models
class MyModel(models.Model):
email = models.CharField(max_length=128, unique=True)
As specified in the documentation:
Field.unique
If
True
, this field must be unique throughout the table.This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a
django.db.IntegrityError
will be raised by the model’ssave()
method.This option is valid on all field types except
ManyToManyField
andOneToOneField
.Note that when unique is True, you don’t need to specify
db_index
, because unique implies the creation of an index.
So here for every two different MyModel
objects, we know that their email
field will contain a different value.
Upvotes: 2