Django模型,循环外键

Django模型,循环外键,django,django-models,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) ## o

如何对以下关系建模:

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
另见:


可以工作,但需要添加相关的\u name参数。已编辑解决方案以包含此内容。