簡體   English   中英

Django 模型中每個外鍵的唯一字段

[英]Unique field in Django Model for each foreign key

我正在定義一組模型,它們相互引用。 它們是文檔應用程序的模型,如下所示

class Document(models.Model):
    text = models.TextField()

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

我希望每個文檔的整數字段都是唯一的,但我不知道該怎么做。 我知道每個字段都有一個唯一的參數,但似乎整個表都是唯一的,這不是我想要的。

您可以在模型中一起使用 unique 是元:

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

    class Meta:
        unique_together = (("doc", "chapter"),)  

這是文檔

(Django的3.1)編輯:使用unique_together現在由文檔氣餒並且可以在將來被棄用,具體根據文檔 使用 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