Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django唯一关系不是唯一表_Python_Django_Django Models_Unique - Fatal编程技术网

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'),)