Fix Trunc database function with tzinfo parameter#296
Conversation
7b00206 to
a7bfe4a
Compare
| value = value.astimezone(self.tzinfo) | ||
| elif isinstance(value, datetime): | ||
| if value is None: | ||
| pass |
There was a problem hiding this comment.
This line isn't reachable I think. If value were None, cannot be instance of date
|
|
||
| def trunc_convert_value(self, value, expression, connection): | ||
| if connection.vendor == "mongodb": | ||
| # A custom TruncBase.convert_value() for MongoDB. |
There was a problem hiding this comment.
I think this logic could be refactored
But dont know how, at least If value none, return
There was a problem hiding this comment.
This part does two things, astimezone and time (one or none)
To check if they must be applied, an code like
if convert_to_tz and isinstance(value, datetime):
if isinstance(self.output_type, DatetimeField | DateField | TimeField):
value = value.astimezone(self.tzinfo)
if isinstance(self.output_type, DateField):
value = value.date()
elif isinstance(self.output_field, TimeField):
value = value.time()
return value
Does this code make sense?
I am assuming that datetimefield implies a datetime value
There was a problem hiding this comment.
Yes, that looks logically correct, but it doesn't short-circuit as much and therefore has some extra isinstance() calls in some cases. (By the way, here's the original method: https://github.com/django/django/blob/9d93e35c207a001de1aa9ca9165bdec824da9021/django/db/models/functions/datetime.py#L345-L364. As you said, there's at least the issue of the unneeded None check under isinstance(value, datetime) there.)
edit: Actually, it's not correct, .date() and .time() truncations are needed even when convert_to_tz=False.
There was a problem hiding this comment.
Oh right. I think it could be "untabbed" but in that way the code isn't much simple
Add the same exception raising from TruncDate to TruncTime and add tests for both functions.
| from .models import DTModel | ||
|
|
||
|
|
||
| @override_settings(USE_TZ=True) |
There was a problem hiding this comment.
Is this setting needed to raise the exception?
There was a problem hiding this comment.
No description provided.