Skip to content

Commit

Permalink
better approach for TruncDate
Browse files Browse the repository at this point in the history
  • Loading branch information
timgraham committed Dec 20, 2024
1 parent dfadf99 commit 28c082c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
6 changes: 0 additions & 6 deletions django_mongodb/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
16 changes: 14 additions & 2 deletions django_mongodb/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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",
Expand Down

0 comments on commit 28c082c

Please sign in to comment.