我目前正在学习Django,并且正在尝试为国家和城市建模。一个国家有许多城市,其中一个(只有一个)是首都。到目前为止,我已经提出了这个建议:
class Country(models.Model):
name = models.CharField(max_length=40)
class City(models.Model):
name = models.CharField(max_length=40)
country = models.ForeignKey('Country')
如何将首都部分纳入模型?谢谢。
答案 0 :(得分:0)
您可以使用递归模型,例如:
class Place(models.Model):
name = models.CharField(max_length=40)
place_parent = models.ForeignKey('self', blank=True, null=True)
is_capital = models.BooleanField(default=False)
创建国家,州,城市...
country = Place()
country.name = 'Ecuador'
country.save()
state = Place()
state.name = 'Pichincha'
state.place_parent_id = country.id
state.save()
city = Place()
city.name = 'Quito'
city.place_parent_id = state.id
city.is_capital = True
city.save()
city2 = Place()
city2.name = 'Other city'
city2.place_parent_id = state.id
city2.is_capital = False
city2.save()
说明:厄瓜多尔有24个州,每个州都有城市,上一个示例的意思是:
country state city
------------------------------
Ecuador / Pichincha / Quito
Ecuador / Pichincha / Other city