63 lines
2.1 KiB
Python
63 lines
2.1 KiB
Python
|
from django.core.management.base import BaseCommand
|
||
|
|
||
|
from pathlib import Path
|
||
|
|
||
|
import right_tree.api.data
|
||
|
from ._spreadsheet_helpers import *
|
||
|
from right_tree.api.models import Habitat, Zone
|
||
|
|
||
|
SPREADSHEET_FILENAME = 'plant_data.xlsx'
|
||
|
SITE_DATA_START_COL = 25
|
||
|
HABITAT_ROW = 1
|
||
|
ZONE_NAME_ROW = 2
|
||
|
ZONE_VARIANT_ROW = 3
|
||
|
ZONE_REFINED_VARIANT_ROW = 5
|
||
|
|
||
|
DATA_DIR_PATH = Path(right_tree.api.data.__file__).resolve().parent
|
||
|
SPREADSHEET = get_spreadsheet(DATA_DIR_PATH, SPREADSHEET_FILENAME)
|
||
|
|
||
|
|
||
|
def load_habitat_zone_data(sheet):
|
||
|
""" Loads habitat and zone objects from data defined in the spreadsheet.
|
||
|
"""
|
||
|
|
||
|
habitats = set()
|
||
|
zones = set()
|
||
|
|
||
|
current_habitat = current_zone = current_variant = current_refined_variant = None
|
||
|
|
||
|
for col in sheet.iter_cols(min_col=SITE_DATA_START_COL, min_row=ZONE_NAME_ROW, max_row=ZONE_REFINED_VARIANT_ROW, values_only=True):
|
||
|
habitat, zone_name, zone_variant, zone_refined_variant = col
|
||
|
|
||
|
if habitat is not None:
|
||
|
current_habitat = habitat
|
||
|
current_zone = current_variant = current_refined_variant = None
|
||
|
|
||
|
current_zone = zone_name if zone_name is not None else current_zone
|
||
|
current_variant = zone_variant if zone_variant is not None else current_variant
|
||
|
current_refined_variant = zone_refined_variant if zone_refined_variant is not None else current_refined_variant
|
||
|
|
||
|
habitats.add(current_habitat)
|
||
|
zones.add((current_zone, current_variant, current_refined_variant))
|
||
|
|
||
|
print("Creating Habitat Objects")
|
||
|
print("--------------------------")
|
||
|
for habitat in habitats:
|
||
|
habitat_obj = Habitat(name=habitat)
|
||
|
habitat_obj.save()
|
||
|
|
||
|
print("Creating Zone Objects")
|
||
|
print("--------------------------")
|
||
|
for zone, variant, refined_variant in zones:
|
||
|
zone_obj = Zone(name=zone, variant=variant,
|
||
|
refined_variant=refined_variant)
|
||
|
zone_obj.save()
|
||
|
|
||
|
|
||
|
class Command(BaseCommand):
|
||
|
help = 'Ingests the site spreadsheet data into the database'
|
||
|
|
||
|
def handle(self, *args, **options):
|
||
|
self.stdout.write('Creating habitat/zone fixtures...')
|
||
|
load_habitat_zone_data(SPREADSHEET)
|