迁移时的 django 错误:“没有唯一约束匹配给定的引用键 table

django error on migration: "There is no unique constraint matching given keys for referenced table

所以我看到在我看到的 Django 方面出现了很多这类问题(很少有人回答)和 none。我很困惑为什么我会收到错误,我猜我在我的字段装饰器上遗漏了一些东西,或者在我的模型定义中没有遗漏什么。这是两个模型......(一个缩写)。我以为我在外键引用的 table 中将唯一键和主键设置为 true,但在迁移时我得到了这个错误:

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

编辑更新代码...

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)

代码快乐,

当您定义一个主键时,它会自动设置为唯一的。所以,只需按照:

class ZoneEntity(models.Model):
    zone_number = models.CharField(max_length=100, primary_key=True)
    ....

class CesiumEntity(models.Model):
    ...
    zone_id = models.ForeignKey('ZoneEntity', null=True, blank=True)
    ...

这会自动绑定ZoneEntity的PK和zone_id!

如果您尝试建立关系的字段不是主键,那么您可以添加 unique=Trueto_field='foo'

 - python manage.py. makemigration
s
Migrations for 'module1':
  0002_auto_20170214_1503.py:
    - Create model CesiumEntity
    - Create model ZoneEntity
    - Add field zone_id to cesiumentity

 - python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, module1, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying module1.0002_auto_20170214_1503... OK

要解决这个问题,需要自己在 postgres table id 上添加唯一约束。

psql <your-database-name>
ALTER TABLE swsite_zoneentity ADD CONSTRAINT zone_unique_id UNIQUE(id);

喜欢this answer

这个问题出现的次数最多是因为您从转储中复制或创建了数据库,并且主键列上的唯一约束(以及其他约束丢失了)。

解决方案:

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