因此,我看到很多这类问题突然出现(很少回答),而在我所看到的Django方面却没有一个。我很困惑为什么我得到错误,我想我在字段装饰器上缺少了某些东西,或者在模型定义中没有了。这是两个模型...(一个缩写)。我以为我在外键引用的一个表中将唯一键和主键设置为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)
最佳答案
Codejoy,
定义主键时,它会自动设置为唯一键。因此,只需执行以下操作:
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绑定(bind)!
如果您尝试建立关系的字段不是主键,则可以添加
unique=True
和to_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
关于python - 迁移: "There is no unique constraint matching given keys for referenced table的django错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42234330/