【发布时间】: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