I am defining a set of models, which have references to each other. They are a model for a documentation app, which is as follows
class Document(models.Model):
text = models.TextField()
class Chapter(models.Model):
doc = models.ForeignKey('Document')
chapter = models.IntegerField()
I want the integer field to be unique per document, but am not sure how to do so. I know there is a unique parameter for each field, but it seems like it is unique for the entire table, which is not what I want.
Of course, you should have an id tag, which is always unique, because it's a primary key. However, certain fields may also need to be unique, because certain fields may need to be unique without any repetition. So, to make a field unique in Django is very basic. You just set the unique attribute to true.
To make fields unique together, we create a class Meta. In this class, we specify the keyword, unique_together, and then create a tuple consisting of all the fields that we want unique together. In this case, we just want 2 fields unique together, but you can specify as many as you want, as long as it's 2 or greater.
A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.
unique_together may be deprecated in the future. This is a list of lists that must be unique when considered together. It's used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).
You can use unique together in your model is meta:
class Chapter(models.Model):
doc = models.ForeignKey('Document')
chapter = models.IntegerField()
class Meta:
unique_together = (("doc", "chapter"),)
Here's the doc
(Django 3.1) edit: Using unique_together is now discouraged by the docs and may be deprecated in the future, as per the docs. Use UniqueConstraint instead:
class Chapter(models.Model):
doc = models.ForeignKey('Document')
chapter = models.IntegerField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=['doc', 'chapter'],
name='unique chapter'
)
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With