Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique field in Django Model for each foreign key

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.

like image 736
user1876508 Avatar asked May 20 '13 16:05

user1876508


People also ask

How can we make unique field in Django model?

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.

How do you make two fields unique in Django?

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.

Is foreign key unique?

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.

What is unique together in Django?

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).


1 Answers

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'
            )
        ]
like image 116
Mounir Avatar answered Oct 06 '22 13:10

Mounir