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

三世轮回 提交于 2019-12-31 04:13:06

问题


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)

回答1:


Codejoy,

When you define a primarykey, it is automatically set as unique.. So, just go by:

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)
    ...

This will automatically bind the PK of ZoneEntity with zone_id!

If the field you are trying to make the relation IS NOT the primary key, then you can add unique=True and 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


来源:https://stackoverflow.com/questions/42234330/django-error-on-migration-there-is-no-unique-constraint-matching-given-keys-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!