Files
consumocuidado-server/core/management/commands/addgeo.py
2021-01-21 13:45:56 +00:00

76 lines
2.8 KiB
Python

import logging
import json
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry, MultiPolygon
from geo.models import City, Region, Province, Country
class Command(BaseCommand):
def handle(self, *args, **kwargs):
logging.info('Deleting all instances of Country, Region, Province, City')
City.objecs.all().delete()
Province.objecs.all().delete()
Region.objecs.all().delete()
Country.objecs.all().delete()
# create country for spain
country = Country.objects.create(name='España')
locations_file = 'locations.json'
locations = json.loads(open(locations_file).read())
# REGIONS
region_counter = 0
geo_file='gadm36_ESP_1.json'
geo_data = json.loads(open(geo_file).read())
for feature in geo_data['features']:
geom = GEOSGeometry(str(feature['geometry']))
if feature['geometry']['type'] == "MultiPolygon":
poly_list = []
for poly in geom:
poly_list.append(poly)
print(poly_list)
else:
poly_list = geom
geom_geos = MultiPolygon(poly_list)
name = feature['properties']['NAME_1']
Region.objects.create(name=name, country=country, geo=geom_geos)
region_counter += 1
"""
for location in locations:
if location['model'] == 'locations.region':
logging.info(f"Creating Region Object {location['fields']['name']}...")
name = location['fields']['name']
Region.objects.create(name=name, country=country, id=location['pk'])
region_counter += 1
"""
# PROVINCES
province_counter = 0
for location in locations:
if location['model'] == 'locations.province':
logging.info(f"Creating Province Object {location['fields']['name']}...")
name = location['fields']['name']
Province.objects.create(name=name, region=Region.objects.get(id=location['fields']['region']), id=location['pk'])
province_counter += 1
# CITIES
city_counter = 0
print('Creating cities...')
for location in locations:
if location['model'] == 'locations.city':
name = location['fields']['name']
City.objects.create(name=name, province=Province.objects.get(id=location['fields']['province']), id=location['pk'])
city_counter += 1
logging.info(f"Region instances created: {region_counter}")
logging.info(f"Province instances created: {province_counter}")
logging.info(f"City instances created: {city_counter}")