From 28c082cd4adb2d5f0972e048a6cbe83f9a25aad3 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Thu, 19 Dec 2024 20:01:58 -0500 Subject: [PATCH] better approach for TruncDate --- django_mongodb/features.py | 6 ------ django_mongodb/functions.py | 16 ++++++++++++++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/django_mongodb/features.py b/django_mongodb/features.py index 71f80be1..7416a5dc 100644 --- a/django_mongodb/features.py +++ b/django_mongodb/features.py @@ -502,12 +502,6 @@ def django_test_expected_failures(self): "db_functions.datetime.test_extract_trunc.DateFunctionTests.test_extract_quarter_func", "db_functions.datetime.test_extract_trunc.DateFunctionTests.test_extract_quarter_func_boundaries", }, - "TruncDate comparison against datetime.date() doesn't work": { - # field__date=date() generates a type mismatch: - # {'$eq': [{'$toDate': '$dt'}, datetime.datetime(2014, 3, 12, 0, 0)]} - # since DatabaseOperations.adapt_datefield_value() converts the date. - "model_fields.test_datetimefield.DateTimeFieldTests.test_lookup_date_without_use_tz", - }, "TruncDate database function with timezone not supported.": { "model_fields.test_datetimefield.DateTimeFieldTests.test_lookup_date_with_use_tz", "timezones.tests.NewDatabaseTests.test_query_convert_timezones", diff --git a/django_mongodb/functions.py b/django_mongodb/functions.py index 9b4f701b..24505179 100644 --- a/django_mongodb/functions.py +++ b/django_mongodb/functions.py @@ -199,7 +199,19 @@ def trunc_date(self, compiler, connection): tzname = self.get_tzname() if tzname and tzname != "UTC": raise NotSupportedError(f"TruncDate with timezone ({tzname}) isn't supported on MongoDB.") - return {"$toDate": lhs_mql} + return { + "$dateFromString": { + "dateString": { + "$concat": [ + {"$dateToString": {"format": "%Y-%m-%d", "date": lhs_mql}}, + # Dates are stored with time(0, 0), so by replacing any + # existing time component with that, the result of + # TruncDate can be compared to DateField. + "T00:00:00.000", + ] + }, + } + } def trunc_time(self, compiler, connection): @@ -208,7 +220,7 @@ def trunc_time(self, compiler, connection): "$dateFromString": { "dateString": { "$concat": [ - # Times are stored with datetime.min.date(), so by + # Times are stored with date(1, 1, 1)), so by # replacing any existing date component with that, the # result of TruncTime can be compared to TimeField. "0001-01-01T",