From f58520303074528415ff4b19fb8a6ac295bb0e35 Mon Sep 17 00:00:00 2001 From: LePetitTim Date: Mon, 17 Jul 2023 11:05:57 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Add=20migration=20generation=20d?= =?UTF-8?q?istance=20to=20source?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0012_generate_distancetosource.py | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 georiviere/main/migrations/0012_generate_distancetosource.py diff --git a/georiviere/main/migrations/0012_generate_distancetosource.py b/georiviere/main/migrations/0012_generate_distancetosource.py new file mode 100644 index 00000000..49381aa9 --- /dev/null +++ b/georiviere/main/migrations/0012_generate_distancetosource.py @@ -0,0 +1,59 @@ +# Generated by Django 3.1.14 on 2023-07-17 08:57 + +from django.conf import settings +from django.contrib.contenttypes.models import ContentType +from django.db import migrations + + +def generate_distancetosource(apps, schema_editor): + Stream = apps.get_model('river', 'Stream') + DistanceToSource = apps.get_model('main', 'DistanceToSource') + from georiviere.main.signals import annotate_distance_to_source + for model in apps.get_models(): + field_names = [field.name for field in model._meta.get_fields()] + if any(i in field_names for i in ['topology', 'geom']) and model._meta.model_name != "stream": + for instance in model.objects.all(): + if instance._meta.model_name in ['morphology', 'status']: + stream = annotate_distance_to_source(Stream.objects.all(), instance).get( + pk=instance.topology.stream_id) + DistanceToSource.objects.update_or_create( + object_id=instance.pk, + content_type_id=ContentType.objects.get(model=instance._meta.model_name).pk, + stream=stream, + defaults={"distance": stream.locate.m} + ) + else: + if not instance.geom: + return Stream.objects.none() + geom = instance.geom + area = geom.buffer(settings.BASE_INTERSECTION_MARGIN) + qs = Stream.objects.all() + if "geom" in [field.name for field in Stream._meta.get_fields()]: + qs = qs.filter(geom__intersects=area) + elif "_geom" in [field.name for field in Stream._meta.get_fields()]: + qs = qs.filter(_geom__intersects=area) + streams = annotate_distance_to_source(qs, instance) + + for stream in streams: + DistanceToSource.objects.update_or_create( + object_id=instance.pk, + content_type_id=ContentType.objects.get_for_model( + instance._meta.model).pk, + stream=stream, + defaults={"distance": stream.locate.m} + ) + DistanceToSource.objects.filter(object_id=instance.pk, + content_type_id=ContentType.objects.get_for_model( + instance._meta.model).pk, + ).exclude(stream__in=streams).delete() + + +class Migration(migrations.Migration): + + dependencies = [ + ('main', '0011_auto_20230602_0901'), + ] + + operations = [ + migrations.RunPython(generate_distancetosource, reverse_code=migrations.RunPython.noop) + ]