【问题标题】:django unique relations not unique tabledjango 唯一关系不是唯一表
【发布时间】: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 实例中不能有重复的名称

示例:

假设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",...)

【问题讨论】:

  • 为该字段添加您自己的验证?

标签: python django django-models unique


【解决方案1】:

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

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

【讨论】:

  • 你能用外键关系来比较表和值吗?如果是这样,这是正确的
猜你喜欢
  • 2018-09-28
  • 2011-09-16
  • 2017-09-17
  • 1970-01-01
  • 2013-09-29
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多