'django error on migration: "There is no unique constraint matching given keys for referenced table
So I have seen that a lot of these kinds of questions have popped up (few answered) and none in a Django aspect that I saw. I am confused why I am getting the error, I am guessing i am missing something on my field decorator or what not in my model definition. Here are the two models... (one abbreviated). I thought I did everything right with unique and primary key set to true in the one table that the foreign key gives reference to but upon migrate I get this error:
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "swsite_zoneentity"
Edit up dated the code ...
class ZoneEntity(models.Model):
zone_number = models.CharField(max_length=100, primary_key=True)
mpoly = models.PolygonField() #this should grow and shrink for the most representative one...
objects = models.GeoManager()
created_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now=True)
class CesiumEntity(models.Model):
be_number = models.CharField(max_length=100) #the number assigned to a foot print to distinguish
#zone_id = models.CharField(max_length=100, null=True, blank=True)
zone_id = models.ForeignKey('ZoneEntity', null=True, blank=True)
Solution 1:[1]
To solve this, needed to add the unique constraint on the postgres table id myself.
psql <your-database-name>
ALTER TABLE swsite_zoneentity ADD CONSTRAINT zone_unique_id UNIQUE(id);
Like this answer
Solution 2:[2]
This problem appears most times because you copied or created your database from a dump and somewhere the unique constraint on your primary key column(as well as other constraints got lost.
Solution:
Open your DB with pg4admin or any client, Databases>your_database>schema>public>tables>your_table right-click
on the table name,
Choose Properties
Select columns tabs
switch primary key on your pk column
save/exit
run migration again
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mahmoud Hanora |
| Solution 2 | Otobong Jerome |
