Skip to content

Commit 28c082c

Browse files
committed
better approach for TruncDate
1 parent dfadf99 commit 28c082c

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

django_mongodb/features.py

-6
Original file line numberDiff line numberDiff line change
@@ -502,12 +502,6 @@ def django_test_expected_failures(self):
502502
"db_functions.datetime.test_extract_trunc.DateFunctionTests.test_extract_quarter_func",
503503
"db_functions.datetime.test_extract_trunc.DateFunctionTests.test_extract_quarter_func_boundaries",
504504
},
505-
"TruncDate comparison against datetime.date() doesn't work": {
506-
# field__date=date() generates a type mismatch:
507-
# {'$eq': [{'$toDate': '$dt'}, datetime.datetime(2014, 3, 12, 0, 0)]}
508-
# since DatabaseOperations.adapt_datefield_value() converts the date.
509-
"model_fields.test_datetimefield.DateTimeFieldTests.test_lookup_date_without_use_tz",
510-
},
511505
"TruncDate database function with timezone not supported.": {
512506
"model_fields.test_datetimefield.DateTimeFieldTests.test_lookup_date_with_use_tz",
513507
"timezones.tests.NewDatabaseTests.test_query_convert_timezones",

django_mongodb/functions.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,19 @@ def trunc_date(self, compiler, connection):
199199
tzname = self.get_tzname()
200200
if tzname and tzname != "UTC":
201201
raise NotSupportedError(f"TruncDate with timezone ({tzname}) isn't supported on MongoDB.")
202-
return {"$toDate": lhs_mql}
202+
return {
203+
"$dateFromString": {
204+
"dateString": {
205+
"$concat": [
206+
{"$dateToString": {"format": "%Y-%m-%d", "date": lhs_mql}},
207+
# Dates are stored with time(0, 0), so by replacing any
208+
# existing time component with that, the result of
209+
# TruncDate can be compared to DateField.
210+
"T00:00:00.000",
211+
]
212+
},
213+
}
214+
}
203215

204216

205217
def trunc_time(self, compiler, connection):
@@ -208,7 +220,7 @@ def trunc_time(self, compiler, connection):
208220
"$dateFromString": {
209221
"dateString": {
210222
"$concat": [
211-
# Times are stored with datetime.min.date(), so by
223+
# Times are stored with date(1, 1, 1)), so by
212224
# replacing any existing date component with that, the
213225
# result of TruncTime can be compared to TimeField.
214226
"0001-01-01T",

0 commit comments

Comments
 (0)