Django 模型,循环外键

标签 django django-models

如何建模以下关系:

class Country(models.Model):
  # The capital city of this country
  capital = models.ForeignKey(City)
  ## other country stuff

class City(models.Model):
  # The country where this city lies in
  country = models.ForeignKey(Country)
  ## other city stuff

这显然不能编译。
(城市在国家的定义中是未定义的)。
有什么建议?

最佳答案

您可以使用字符串而不是模型类来引用模型:

class Country(models.Model):
  # The capital city of this country
  capital = models.ForeignKey('City', related_name='+')
  ## other country stuff

另见:
  • Django models.py Circular Foreign Key
  • Cross-referencing foreign keys in Django 1.4
  • 关于Django 模型,循环外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18966904/

    相关文章:

    python - Django i18n 查找支持的语言

    python - 使用 dictConfig 的 Python 日志记录问题

    python - Django模型实例具体代码

    python - 如何在 Django 基于类的创建 View 中限制每个用户仅允许每 24 小时发帖一次

    django.db.utils.DatabaseError : permission denied for sequence 错误

    python - bool 字段总是保存 False django

    django - 关于 sorl-thumbnail 的知识

    python - 如何将计算结果保存在模型中而不需要重新计算每次调用?

    python - 在 django 自定义用户模型中创建 super 用户,以电话号码作为用户名

    Django - 营业时间的对象