Skip to content

Commit

Permalink
Add data migrations to populate locations
Browse files Browse the repository at this point in the history
  • Loading branch information
norkans7 committed Jan 9, 2025
1 parent 72a8c30 commit 6492f11
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions temba/locations/migrations/0034_populate_locations.py
Original file line number Diff line number Diff line change
@@ -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)]

0 comments on commit 6492f11

Please sign in to comment.