简体   繁体   中英

There is no unique constraint matching given keys for referenced table in django

There are a lot of questions related to this error on SO, but either I understand each of them incorrectly, or they do not apply to this case.

I have the following code in photo/models.py .

class Photo(EmptyModelBase):
    # there's a lot of fields in this model.

And the following in points/models.py

class Label(EmptyModelBase):
    photo = models.ForeignKey(Photo, related_name='labels')

Considering this works, I understand it to mean that the Photo model holds an unique key, since Label can have a photo field with a foreignkey to the Photo model.

So, next I wanted to add another model to points/models.py , that also holds a foreignkey to Photos

class Material(EmptyModelBase):   
    photo = models.ForeignKey(Photo, related_name='material')

When trying to add these changes to the database, I get the following error:

django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "photos_photo"

What I though this error meant is that the Photo model does not have an unique constraint, ie entries in the Photo model are not necessarily unique, therefor the foreignkey might not know which entry to use. However, I can add the foreignkey in Label to the model, so that explanation doesn't appear to make sense.

Extend your models with django.db.models.Model then it will have some unique field in it, say id.

Please refer to documentation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM