forked from rapidpro/rapidpro
-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add data migrations to populate locations
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)] |