1

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

4

1 回答 1

6

您可以将引用模型编写为字符串:

用户/模型.py:

from django.db.models import Model, ForeignKey

class Profile(Model):
    citizenship = ForeignKey('countries.Country')
于 2013-04-28T13:14:31.763 回答