How to add capital to the cities-django-light-country?

I am using django-cities-light (a lighter version of django-cities ) with Django 1.8.x. It defines abstract models of a country, region / state, and city so that we can expand and add custom fields. For example, we can add a time zone to a city by writing a post_import signal handler, as described here .

I also need to add the capital field to each country. I am not very familiar with GeoDjango, and I knew that the django-cities Country application has a field of capital.

+6
source share
2 answers

You need to customize your country model. Let's say you have the "mygeonames" application with models.py:

 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) 

Then in settings.py you should specify CITIES_LIGHT_APP_NAME = 'mygeonames' and put both city_light and mygeonames applications in INSTALLED_APPS

After that, you can transfer your database and run ./manage.py cities_light

At the end, you should get something like this:

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

But instead, you can link to a table of cities.

+5
source

here is an extended idea on @irqed answer:

 class City(AbstractCity): is_capital = models.BooleanField() class Country(AbstractCountry): def capital(self): return self.city_set.filter(is_capital=True) 

* Please note: I am not familiar with this package (I just assume that they used city_set as a sibling name)

Why? Well, for me, capital seems more understandable as an attribute for a city. It can also save some time when trying to work with City objects (let's say you want to check if the city is capital), you do not need to make another query in another table and compare the names, you just check the already extracted Boolean field)

+2
source

Source: https://habr.com/ru/post/989205/


All Articles