django独特的关系不是唯一的表

时间:2013-12-10 19:21:37

标签: python django django-models unique

采用以下模型:

class Foo(models.Model):
    bar = models.ForeignKey(Bar)
    name = models.CharField(max_length=30)
    #...

所以这样做会将Foo模型与Bar模型相关联,并且每个Foo模型都有name

如何才能使其名称仅对连接的Bar模型具有唯一性?

注意:unique=True不会工作,因为名称不需要在整个表中都是唯一的,只是在特定的Bar实例中不能有重复的名称

例如:

我们可以说abBar

的实例
#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",...)

1 个答案:

答案 0 :(得分:3)

也许你谈论这个:https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together

class Meta:
    unique_together = (('bar', 'name'),)