【问题标题】:Can I use the field of a related model in a Django UniqueConstraint?我可以在 Django UniqueConstraint 中使用相关模型的字段吗?
【发布时间】:2020-03-19 17:50:18
【问题描述】:

是否可以使用外键模型的字段制作UniqueConstraint

例如,我如何限制同一年龄作者撰写的所有书籍都有一个唯一的标题? (一个人为的例子,但你明白了。

models.py

class Author(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

class Book(models.Model):
    class Meta:
        contraints = [
            models.UniqueConstraint(
                # THIS DOESN'T WORK
                fields=["author__age", "title"],
                name="my_constraint",
            )
        ]
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, related_name="books")

这会产生以下错误:

django.core.exceptions.FieldDoesNotExist:图书没有名为“author__age”的字段

'

【问题讨论】:

    标签: django django-models unique-constraint


    【解决方案1】:

    不,UniqueConstraint 还不能那样工作。 See this answer 了解可能的替代方案。

    【讨论】:

    • 谢谢。这有帮助。在我的真实代码中,author.age 实际上是另一个外键,所以我只是在该模型上设置了一个UniqueConstraint
    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 2014-07-10
    • 2011-09-30
    • 2013-08-13
    • 2015-03-14
    • 2020-09-14
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多