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

前端 未结 2 955
误落风尘
误落风尘 2021-01-20 02:54

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 g

相关标签:
2条回答
  • 2021-01-20 03:39

    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
    
    0 讨论(0)
  • 2021-01-20 03:41

    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

    0 讨论(0)
提交回复
热议问题