diff options
Diffstat (limited to 'archaeological_context_records/models.py')
-rw-r--r-- | archaeological_context_records/models.py | 34 |
1 files changed, 25 insertions, 9 deletions
diff --git a/archaeological_context_records/models.py b/archaeological_context_records/models.py index a14605a5f..0c63ed8e9 100644 --- a/archaeological_context_records/models.py +++ b/archaeological_context_records/models.py @@ -389,7 +389,7 @@ class GeographicSubTownItem(GeoItem): def post_save_geo(self, save=True): # manage geodata towns - if getattr(self, "_post_save_geo_ok", False): + if getattr(self, "_post_save_geo_ok", False) or not self.pk: # prevent infinite loop - should not happen, but... return self._post_save_geo_ok = True @@ -414,15 +414,31 @@ class GeographicSubTownItem(GeoItem): self.main_geodata = None modified = True + current_model = self.__class__ + main_item_is_set = current_model.objects.filter( + id=self.pk, + main_geodata__source_content_type__app_label=current_model._meta.app_label, + main_geodata__source_content_type__model=current_model._meta.model_name, + ).count() # main geo is set for the current model + for upper_attr in self.UPPER_GEO: - upper = getattr(self, upper_attr, None) - if upper and upper.main_geodata and \ - upper.main_geodata_id not in self.geodata.values_list( - "id", flat=True): - modified = True - self.geodata.add(upper.main_geodata) - if not self.main_geodata: - self.main_geodata = upper.main_geodata + q_dict = {"id": self.pk, f"{upper_attr}__main_geodata_id__isnull": False} + q = current_model.objects.filter(**q_dict) + if q.count(): + upper = None + main_geodata_id = q.values_list(f"{upper_attr}__main_geodata_id", flat=True)[0] + if main_geodata_id not in self.geodata.values_list("id", flat=True): + upper = getattr(self, upper_attr, None) + modified = True + self.geodata.add(upper.main_geodata) + + if not main_item_is_set: + if self.main_geodata_id != main_geodata_id: + if not upper: + upper = getattr(self, upper_attr, None) + modified = True + self.main_geodata = upper.main_geodata + main_item_is_set = True if modified and save: if settings.USE_BACKGROUND_TASK and hasattr(self, "no_post_process"): |