From 692f43a6ae230c3738a7564e877dbcf2fb6e48ce Mon Sep 17 00:00:00 2001 From: eatyourpeas Date: Fri, 30 Aug 2024 22:05:13 +0100 Subject: [PATCH] updates save and update methods in Organisation --- .../hospitals/models/organisation.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/rcpch_nhs_organisations/hospitals/models/organisation.py b/rcpch_nhs_organisations/hospitals/models/organisation.py index f9eea4b..b5c67d3 100644 --- a/rcpch_nhs_organisations/hospitals/models/organisation.py +++ b/rcpch_nhs_organisations/hospitals/models/organisation.py @@ -6,6 +6,9 @@ FloatField, BooleanField, ) +from django.contrib.gis.geos import Point +from django.db.models.signals import pre_save +from django.dispatch import receiver # 3rd party from .time_and_user_abstract_base_classes import TimeStampAbstractBaseClass @@ -130,3 +133,25 @@ class Meta: def __str__(self) -> str: return self.name + + def save(self, *args, **kwargs): + if self.latitude and self.longitude and not self.geocode_coordinates: + self.geocode_coordinates = Point( + x=self.longitude, y=self.latitude, srid=4326 + ) + super(Organisation, self).save(*args, **kwargs) + + +# This ensures that the geocode coordinates are set before saving, even if update is called +@receiver(pre_save, sender=Organisation) +def set_geocode_coordinates(sender, instance, **kwargs): + from django.contrib.gis.geos import Point + + if instance.latitude and instance.longitude and not instance.geocode_coordinates: + instance.geocode_coordinates = Point( + x=instance.longitude, y=instance.latitude, srid=4326 + ) + + +# Ensure the signal is connected +pre_save.connect(set_geocode_coordinates, sender=Organisation)