From aa57c6e101ca6c805ef115f5901d5b98646f3efa Mon Sep 17 00:00:00 2001 From: Dana Lambert Date: Fri, 15 Oct 2021 14:39:03 +1300 Subject: [PATCH] Add django command to populate the database with shapefile data --- backend/right_tree/api/management/__init__.py | 0 .../api/management/commands/loadshapefiles.py | 44 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 backend/right_tree/api/management/__init__.py create mode 100644 backend/right_tree/api/management/commands/loadshapefiles.py diff --git a/backend/right_tree/api/management/__init__.py b/backend/right_tree/api/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/right_tree/api/management/commands/loadshapefiles.py b/backend/right_tree/api/management/commands/loadshapefiles.py new file mode 100644 index 0000000..4fa9f96 --- /dev/null +++ b/backend/right_tree/api/management/commands/loadshapefiles.py @@ -0,0 +1,44 @@ +from django.core.management.base import BaseCommand +from django.contrib.gis.utils import LayerMapping + +from pathlib import Path + +import right_tree.api.data +from right_tree.api.models import SoilLayer, EcologicalDistrictLayer + +# Auto-generated `LayerMapping` dictionary for SoilLayers model +soillayer_mapping = { + 'nzsc_class': 'nzsc_class', + 'nzsc_group': 'nzsc_group', + 'nzsc_order': {'code': 'nzsc_order'}, + 'shape_leng': 'SHAPE_Leng', + 'geom': 'POLYGON', +} + +# Auto-generated `LayerMapping` dictionary for ecologicaldistrictlayer model +ecologicaldistrictlayer_mapping = { + 'ecological': 'ECOLOGICAL', + 'ecologic_1': 'ECOLOGIC_1', + 'ecologic_2': {'name': 'ECOLOGIC_2'}, + 'shape_leng': 'SHAPE_Leng', + 'shape_area': 'SHAPE_Area', + 'geom': 'POLYGON', +} + +# Shapefiles +soillayer_shp = Path(right_tree.api.data.__file__).resolve().parent / 'resources' / 'fundamental_soil_layers' / 'fundamental-soil-layers-new-zealand-soil-classification.shp' +ecologicaldistrictlayer_shp = Path(right_tree.api.data.__file__).resolve().parent / 'resources' / 'ecological_districts' / 'DOC_EcologicalDistricts_2021_08_02.shp' + +class Command(BaseCommand): + help = 'Ingests the shapefile data for ecological regions and soil layers.' + + def handle(self, *args, **options): + self.stdout.write('Loading soil layers...') + soil_lm = LayerMapping(SoilLayer, soillayer_shp, soillayer_mapping, transform=False) + soil_lm.save(strict=True) + self.stdout.write(self.style.SUCCESS('Soil layers loaded succesfully.')) + + self.stdout.write('Loading ecological district layers...') + ecologicaldistrictlayer_lm = LayerMapping(EcologicalDistrictLayer, ecologicaldistrictlayer_shp, ecologicaldistrictlayer_mapping, transform=False) + ecologicaldistrictlayer_lm.save(strict=True) + self.stdout.write(self.style.SUCCESS('Ecological district layers loaded succesfully.'))