且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django 1.4中交叉引用外键

更新时间:2023-02-02 23:20:58

您可以将引用的模型写入字符串:



users / models.py:

 从django.db.models导入模型,ForeignKey 

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


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

You can write referenced models as string:

users/models.py:

from django.db.models import Model, ForeignKey

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