【问题标题】:Modelling Countries and Cities模拟国家和城市
【发布时间】:2018-11-11 14:33:34
【问题描述】:

我目前正在学习 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')

如何将首都部分合并到模型中?谢谢。

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您可以使用递归模型,例如:

    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
    

    【讨论】:

    • 这个解决方案和解释太棒了。非常感谢您花时间回答我发布的问题。
    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2014-09-08
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多