Cross-referencing foreign keys in Django 1.4

◇◆丶佛笑我妖孽 提交于 2019-12-23 03:37:08

问题


I have a Django project where I would need two models to have a foreign key to each other. However this is not possible because two Python files would have to import each other which Python doesn't allow. What is the best way to solve this problem?

So my code currently looks like this:

countries/models.py:

from django.db.models import Model, ForeignKey
from users.models import Profile

class Country(Model):
    president = ForeignKey(Profile)

users/models.py:

from django.db.models import Model, ForeignKey
from countries.models import Country

class Profile(Model):
    citizenship = ForeignKey(Country)

Error given is: ImportError: cannot import name Profile


回答1:


You can write referenced models as string:

users/models.py:

from django.db.models import Model, ForeignKey

class Profile(Model):
    citizenship = ForeignKey('countries.Country')


来源:https://stackoverflow.com/questions/16263219/cross-referencing-foreign-keys-in-django-1-4

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