Python django中引用表的给定键不匹配唯一约束
关于这一错误有很多问题,但要么我理解错误,要么它们不适用于本案例 我在Python django中引用表的给定键不匹配唯一约束,python,django,Python,Django,关于这一错误有很多问题,但要么我理解错误,要么它们不适用于本案例 我在photo/models.py中有以下代码 class Photo(EmptyModelBase): # there's a lot of fields in this model. 以及points/models.py中的以下内容 class Label(EmptyModelBase): photo = models.ForeignKey(Photo, related_name='labels') 考虑到
photo/models.py
中有以下代码
class Photo(EmptyModelBase):
# there's a lot of fields in this model.
以及points/models.py中的以下内容
class Label(EmptyModelBase):
photo = models.ForeignKey(Photo, related_name='labels')
考虑到这一点,我理解这意味着Photo
模型拥有一个唯一的键,因为Label
可以有一个Photo
字段,其中包含一个指向Photo
模型的外键
因此,接下来我想在points/models.py
中添加另一个模型,该模型还包含Photos
的外键
class Material(EmptyModelBase):
photo = models.ForeignKey(Photo, related_name='material')
尝试将这些更改添加到数据库时,出现以下错误:
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "photos_photo"
我认为此错误的意思是照片模型没有唯一约束,即照片模型中的条目不一定是唯一的,因此foreignkey可能不知道使用哪个条目。但是,我可以将foreignkey in标签添加到模型中,这样解释就没有意义了。使用django.db.models.model扩展您的模型,然后它会有一些唯一的字段,比如id
请参阅文档问题在于照片模型中没有唯一的密钥。照片模型内有主钥匙吗?您在哪里定义了EmptyModelBase,它是一个抽象类吗?photo
模型中存在一个唯一的键,即它保存id
。因此,我感到困惑的是,可以在标签
上创建外键,但不能在材质
上创建外键,因为标签
类确实有效,这是否意味着照片
中已经有一个唯一的字段?当材料
不能工作时,标签
如何工作?