From 2e5491f7064084a5c1a841692dfc9f7279d32f04 Mon Sep 17 00:00:00 2001 From: Andy Babic Date: Sat, 17 Feb 2024 10:46:24 +0000 Subject: [PATCH] Give extract_field_value() the ability to detect and handle transform expressions for date, time and datetime field values --- modelcluster/utils.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/modelcluster/utils.py b/modelcluster/utils.py index 5f4a964..5acb8b8 100644 --- a/modelcluster/utils.py +++ b/modelcluster/utils.py @@ -1,3 +1,4 @@ +import datetime from functools import lru_cache from django.core.exceptions import FieldDoesNotExist from django.db.models import ( @@ -138,7 +139,22 @@ def extract_field_value(obj, key, pk_only=False, suppress_fielddoesnotexist=Fals latest_obj = obj segments = key.split(REL_DELIMETER) for i, segment in enumerate(segments, start=1): - if hasattr(source, segment): + if ( + isinstance(source, datetime.date) + and segment in datetime_utils.DATEFIELD_TRANSFORM_EXPRESSIONS + ): + source = datetime_utils.derive_from_date(source, segment) + elif ( + isinstance(source, datetime.time) + and segment in datetime_utils.TIMEFIELD_TRANSFORM_EXPRESSIONS + ): + source = datetime_utils.derive_from_time(source, segment) + elif ( + isinstance(source, datetime.datetime) + and segment in datetime_utils.DATETIMEFIELD_TRANSFORM_EXPRESSIONS + ): + source = datetime_utils.derive_from_datetime(source, segment) + elif hasattr(source, segment): value = getattr(source, segment) if isinstance(value, Model): latest_obj = value @@ -155,7 +171,6 @@ def extract_field_value(obj, key, pk_only=False, suppress_fielddoesnotexist=Fals ) ) source = value - continue elif suppress_fielddoesnotexist: return None else: