如何建模以下关系:
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 模型,循环外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18966904/