Skip to content

Commit

Permalink
add TruncTime support
Browse files Browse the repository at this point in the history
  • Loading branch information
timgraham committed Dec 19, 2024
1 parent a0be764 commit 5c34718
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,6 @@ Congratulations, your project is ready to go!
- `SHA1`, `SHA224`, `SHA256`, `SHA384`, `SHA512`
- `Sign`
- `TruncDate`
- `TruncTime`

- The `tzinfo` parameter of the `Trunc` database functions doesn't work
properly because MongoDB converts the result back to UTC.
Expand Down
5 changes: 0 additions & 5 deletions django_mongodb/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,11 +503,6 @@ def django_test_expected_failures(self):
"model_fields.test_datetimefield.DateTimeFieldTests.test_lookup_date_without_use_tz",
"timezones.tests.NewDatabaseTests.test_query_convert_timezones",
},
"TruncTime database function not supported.": {
"db_functions.datetime.test_extract_trunc.DateFunctionTests.test_trunc_time_comparison",
"db_functions.datetime.test_extract_trunc.DateFunctionTests.test_trunc_time_func",
"db_functions.datetime.test_extract_trunc.DateFunctionTests.test_trunc_time_none",
},
"MongoDB can't annotate ($project) a function like PI().": {
"aggregation.tests.AggregateTestCase.test_aggregation_default_using_decimal_from_database",
"db_functions.math.test_pi.PiTests.test",
Expand Down
19 changes: 19 additions & 0 deletions django_mongodb/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
Now,
TruncBase,
TruncDate,
TruncTime,
)
from django.db.models.functions.math import Ceil, Cot, Degrees, Log, Power, Radians, Random, Round
from django.db.models.functions.text import (
Expand Down Expand Up @@ -199,6 +200,23 @@ def trunc_date(self, compiler, connection):
return {"$toDate": lhs_mql}


def trunc_time(self, compiler, connection):
lhs_mql = process_lhs(self, compiler, connection)
return {
"$dateFromString": {
"dateString": {
"$concat": [
# Times are stored with datetime.min.date(), so by
# replacing any existing date component with that, the
# result of TruncTime can be compared to TimeField.
"0001-01-01T",
{"$dateToString": {"format": "%H:%M:%S.%L", "date": lhs_mql}},
]
}
}
}


def register_functions():
Cast.as_mql = cast
Concat.as_mql = concat
Expand All @@ -221,4 +239,5 @@ def register_functions():
Trim.as_mql = trim("trim")
TruncBase.as_mql = trunc
TruncDate.as_mql = trunc_date
TruncTime.as_mql = trunc_time
Upper.as_mql = preserve_null("toUpper")

0 comments on commit 5c34718

Please sign in to comment.