From 0d622302ac1349856e7f021b386b28c4ec9e9f31 Mon Sep 17 00:00:00 2001 From: Emmy D'Anello Date: Sun, 12 May 2024 17:11:54 +0200 Subject: [PATCH] Preserve last_modified and etag fields after reloading GTFS Feeds --- trainvel/gtfs/apps.py | 6 ++++++ trainvel/gtfs/signals.py | 14 ++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 trainvel/gtfs/signals.py diff --git a/trainvel/gtfs/apps.py b/trainvel/gtfs/apps.py index 238230d..0dc8df4 100644 --- a/trainvel/gtfs/apps.py +++ b/trainvel/gtfs/apps.py @@ -1,4 +1,5 @@ from django.apps import AppConfig +from django.db.models.signals import pre_save from django.utils.translation import gettext_lazy as _ @@ -6,3 +7,8 @@ class TrainvelGTFSConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "trainvel.gtfs" verbose_name = _("Trainvel - GTFS") + + def ready(self): + from trainvel.gtfs import signals + + pre_save.connect(signals.keep_gtfs_feed_modification_date, sender="gtfs.GTFSFeed") diff --git a/trainvel/gtfs/signals.py b/trainvel/gtfs/signals.py new file mode 100644 index 0000000..3e339f0 --- /dev/null +++ b/trainvel/gtfs/signals.py @@ -0,0 +1,14 @@ +from trainvel.gtfs.models import GTFSFeed + + +def keep_gtfs_feed_modification_date(instance: GTFSFeed, raw: bool = True, **_kwargs): + """ + Keep the last_modified and etag fields from the existing GTFSFeed instance when saving a new one. + """ + if raw and GTFSFeed.objects.filter(pk=instance.pk).exists(): + # If a GTFSFeed instance is being saved from a raw query, + # we want to keep the last_modified and etag fields from the existing instance. + # This is useful when loading initial data from a fixture, for example. + old_instance = GTFSFeed.objects.get(pk=instance.pk) + instance.last_modified = old_instance.last_modified + instance.etag = old_instance.etag