python - 如何为 django-cities-light country 模型添加资本?

标签 python django timezone countries django-countries

我正在使用 django-cities-light (django-cities 的较轻版本)与 Django 1.8.x。它定义了Country、Region/State和City的抽象模型,方便我们扩展和添加自定义字段。例如,我们可以通过编写 post_import 信号处理程序将时区添加到城市,如 here 所述。 .

同样,我需要为每个国家/地区添加字段 capital。我对 GeoDjango 不太熟悉,我知道 django-cities 应用程序的 Country 有大写字段。

最佳答案

您需要设置自定义国家/地区模型。 假设您有一个带有 models.py 的应用程序“mygeonames”:

import cities_light

from django.db import models

from cities_light.settings import ICountry
from cities_light.receivers import connect_default_signals
from cities_light.abstract_models import (AbstractCountry, AbstractRegion,
    AbstractCity)

class Country(AbstractCountry):
    capital = models.CharField(max_length=50)
connect_default_signals(Country)


class Region(AbstractRegion):
    pass
connect_default_signals(Region)


class City(AbstractCity):
    pass
connect_default_signals(City)


def process_country_import(sender, instance, items, **kwargs):
    instance.capital = items[ICountry.capital]

cities_light.signals.country_items_post_import.connect(process_country_import)

然后在 settings.py 中,您应该指定 CITIES_LIGHT_APP_NAME = 'mygeonames',并将应用程序 'cities_light' 和 'mygeonames' 都放入 INSTALLED_APPS

之后你可以迁移你的数据库并运行./manage.py cities_light

最后你应该得到这样的东西:

In [1]: from mygeonames.models import Country
In [2]: cc = Country.objects.all()
In [3]: cc[0].capital
Out[3]: u'Paris'

但您可能希望链接到 Cities 表。

关于python - 如何为 django-cities-light country 模型添加资本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30865074/

相关文章:

具有异步的 Python 事件处理程序(非阻塞 while 循环)

django - 我如何使用 Model._meta.get.fields() 读取模型中的所有字段

java - 通过时区偏移量获取TimeZone

powershell - 尝试使用Windows Powershell在Python 3中上载特定字符

python - 我如何告诉 OSX 使用brew 中的matplotlib,而不是默认的?

python - Django 模型可以有硬编码的无类型字段吗?

c# - TimeZoneInfo Id 取决于机器?

internationalization - Web 应用程序测试的假时区

python - 如何根据python中的某些条件在argparser中使位置参数可选

django - urls.py - 将/页面重定向到另一个应用程序