Python django唯一关系不是唯一表
以以下模型为例:Python django唯一关系不是唯一表,python,django,django-models,unique,Python,Django,Django Models,Unique,以以下模型为例: class Foo(models.Model): bar = models.ForeignKey(Bar) name = models.CharField(max_length=30) #... 因此,这样做的目的是将Foo模型连接到Bar模型,每个Foo模型都有一个名称 我如何才能使其名称仅与连接的条型号相关? 注意:unique=True不起作用,因为名称不需要在整个表中都是唯一的,只是在特定的Bar实例中不能有重复的名称 例子: 假设a和b是Ba
class Foo(models.Model):
bar = models.ForeignKey(Bar)
name = models.CharField(max_length=30)
#...
因此,这样做的目的是将Foo
模型连接到Bar
模型,每个Foo
模型都有一个名称
我如何才能使其名称仅与连接的条
型号相关?
注意: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",...)
也许你会说:
为该字段添加您自己的验证?您可以使用外键关系来比较表和值吗?如果是这样,这是正确的
class Meta:
unique_together = (('bar', 'name'),)