简体   繁体   English

Django 模型中每个外键的唯一字段

[英]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:您可以在模型中一起使用 unique 是元:

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 . (Django的3.1)编辑:使用unique_together现在由文档气馁并且可以在将来被弃用,具体根据文档 Use UniqueConstraint instead:使用 UniqueConstraint 代替:

class Chapter(models.Model):
    doc = models.ForeignKey('Document')
    chapter = models.IntegerField()

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['doc', 'chapter'], 
                name='unique chapter'
            )
        ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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