【发布时间】:2013-12-10 19:21:36
【问题描述】:
采取以下模型:
class Foo(models.Model):
bar = models.ForeignKey(Bar)
name = models.CharField(max_length=30)
#...
所以它的作用是将Foo 模型连接到Bar 模型,并且每个Foo 模型都有一个name。
我怎样才能使名称仅对于连接的Bar 模型是唯一的??
注意:unique=True 不起作用,因为名称不需要在整个表中是唯一的,只是在特定的 Bar 实例中不能有重复的名称
示例:
假设a 和b 是Bar 的实例
#the following is allowed
c = Foo(bar = a, name="foobar",...)
d = Foo(bar = b, name="foobar",...)
e = Foo(bar = b, name="barfoo",...)
#the following would not be allowed because
#an instance already exists in `a` with the name "foobar"
f = Foo(bar = a, name="foobar",...)
【问题讨论】:
-
为该字段添加您自己的验证?
标签: python django django-models unique