【问题标题】:Django Models, cyclic foreign keysDjango 模型,循环外键
【发布时间】:2013-09-28 19:13:38
【问题描述】:

如何建模以下关系:

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

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

【问题讨论】:

    标签: django django-models


    【解决方案1】:

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

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

    另见:

    【讨论】:

    • 有效,但需要添加related_name参数。编辑解决方案以包含此内容。
    猜你喜欢
    • 2011-04-10
    • 2013-01-17
    • 2014-03-10
    • 2019-07-19
    • 2015-01-29
    • 2020-11-13
    • 2011-11-29
    • 2016-05-25
    • 2015-03-07
    相关资源
    最近更新 更多