【问题标题】:Cross-referencing foreign keys in Django 1.4Django 1.4 中的交叉引用外键
【发布时间】:2013-04-28 13:11:23
【问题描述】:

我有一个 Django 项目,我需要两个模型才能相互拥有外键。然而,这是不可能的,因为两个 Python 文件必须相互导入,而 Python 不允许这样做。解决这个问题的最佳方法是什么?

所以我的代码目前看起来像这样:

国家/模型.py:

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

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

用户/模型.py:

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

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

给出的错误是:ImportError: cannot import name Profile

【问题讨论】:

    标签: python django database-design django-1.4 schema-design


    【解决方案1】:

    你可以将引用的模型写成字符串:

    用户/模型.py:

    from django.db.models import Model, ForeignKey
    
    class Profile(Model):
        citizenship = ForeignKey('countries.Country')
    

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 2013-11-11
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2012-05-17
      • 2013-02-23
      • 2017-01-22
      相关资源
      最近更新 更多