2013-09-23 158 views
4

如何建模以下关系:Django模型,循环外键

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 

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

回答

3

你可以参考模型使用字符串,而不是一个模型类:

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

另见:

+0

作品,但需要添加related_name参数。编辑解决方案以包含此内容。 – Scrontch

+0

@Scrontch增加了'related_name'参数,谢谢。 – alecxe