From 066b4ae3d641856aa5dd663b94a394c9d16f4f7e Mon Sep 17 00:00:00 2001 From: Birger Schacht Date: Thu, 29 Aug 2024 12:51:28 +0200 Subject: [PATCH] feat(generic): add DateTimeIntervalCharField --- apis_core/generic/fields.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 apis_core/generic/fields.py diff --git a/apis_core/generic/fields.py b/apis_core/generic/fields.py new file mode 100644 index 000000000..0049d47bd --- /dev/null +++ b/apis_core/generic/fields.py @@ -0,0 +1,23 @@ +from django.db.models import DateTimeField, CharField + + +class StringDateTimeField(CharField): + """ A simple CharField, that populates datetime fields with its own value """ + def pre_save(self, model_instance, add): + name = self.attname.removesuffix('_string') + value = getattr(model_instance, self.attname) + if hasattr(model_instance, f'{name}_datetime'): + setattr(model_instance, f'{name}_datetime', value) + if hasattr(model_instance, f'{name}_datetime_from'): + setattr(model_instance, f'{name}_datetime_from', value) + if hasattr(model_instance, f'{name}_datetime_to'): + setattr(model_instance, f'{name}_datetime_to', value) + return super().pre_save(model_instance, add) + + +class DateTimeIntervalCharField: + def contribute_to_class(self, cls, name): + StringDateTimeField(max_length=255, blank=True, null=True).contribute_to_class(cls, f'{name}_string') + DateTimeField(editable=False, blank=True, null=True).contribute_to_class(cls, f'{name}_datetime') + DateTimeField(editable=False, blank=True, null=True).contribute_to_class(cls, f'{name}_datetime_from') + DateTimeField(editable=False, blank=True, null=True).contribute_to_class(cls, f'{name}_datetime_to')