From 0316ff9243a008ab5ea9f099f597994f6a9dc52d Mon Sep 17 00:00:00 2001 From: Norbert Kwizera Date: Thu, 9 Jan 2025 13:44:49 +0200 Subject: [PATCH] Add data migrations to populate locations --- .../migrations/0034_populate_locations.py | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 temba/locations/migrations/0034_populate_locations.py diff --git a/temba/locations/migrations/0034_populate_locations.py b/temba/locations/migrations/0034_populate_locations.py new file mode 100644 index 0000000000..15655a62fe --- /dev/null +++ b/temba/locations/migrations/0034_populate_locations.py @@ -0,0 +1,55 @@ +# Generated by Django 5.1.4 on 2025-01-09 10:50 +import geojson + +from django.db import migrations + + +def populate_locations(apps, schema_editor): + Org = apps.get_model("orgs", "Org") + AdminBoundary = apps.get_model("locations", "AdminBoundary") + BoundaryAlias = apps.get_model("locations", "BoundaryAlias") + Location = apps.get_model("locations", "Location") + LocationAlias = apps.get_model("locations", "LocationAlias") + + location_id_by_boundary_id = {} + location_id_by_country_id = {} + + boundaries = AdminBoundary.objects.all().order_by("level", "osm_id").select_related("parent") + for boundary in boundaries: + geometry = geojson.loads(boundary.simplified_geometry.geojson) + obj = Location.objects.create( + osm_id=boundary.osm_id, + name=boundary.name, + level=boundary.level, + parent_id=None if not boundary.parent else location_id_by_boundary_id[boundary.parent_id], + path=boundary.path, + simplified_geometry=geometry, + lft=boundary.lft, + rght=boundary.rght, + tree_id=boundary.tree_id, + ) + location_id_by_boundary_id[boundary.id] = obj.id + if boundary.level == 0: + location_id_by_country_id[boundary.id] = obj.id + + orgs = Org.objects.all().exclude(country=None) + for org in orgs: + org.location_id = location_id_by_country_id[org.country_id] + org.save(update_fields=("location_id",)) + + aliases = BoundaryAlias.objects.filter(org=org) + for alias in aliases: + LocationAlias.objects.create( + org=org, + location_id=location_id_by_boundary_id[alias.boundary_id], + name=alias.name, + ) + + +class Migration(migrations.Migration): + + dependencies = [ + ("locations", "0033_location_locationalias_location_locations_by_name_and_more"), + ] + + operations = [migrations.RunPython(populate_locations, migrations.RunPython.noop)]