gpt4 book ai didi

python - Django唯一关系不是唯一表

转载 作者:行者123 更新时间:2023-11-30 23:30:34 25 4
gpt4 key购买 nike

采用以下模型:

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

最佳答案

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

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

关于python - Django唯一关系不是唯一表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20503389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com