简体   繁体   中英

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.

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'
            )
        ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM