Skip to content

Commit

Permalink
Don't evaluate default_timezone unless needed (#8531)
Browse files Browse the repository at this point in the history
If you set a custom timezone for a DateTimeField, the function
self.default_timezone() is still called, since fallback params to
getattr are still evaluated.

This rewrites to use hasattr, so the fallback case is only executed if
it will actually be used. If you render a lot of DateTimeFields in a
serializer, the time spent evaluating default_timezone() once for each
of them can accumulate to quite a bit, which is just unused work in the
case where timezone is already specified on the field.
  • Loading branch information
stianjensen authored Jun 24, 2022
1 parent fa9d516 commit dba9493
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1179,7 +1179,7 @@ def enforce_timezone(self, value):
When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes.
"""
field_timezone = getattr(self, 'timezone', self.default_timezone())
field_timezone = self.timezone if hasattr(self, 'timezone') else self.default_timezone()

if field_timezone is not None:
if timezone.is_aware(value):
Expand Down

0 comments on commit dba9493

Please # to comment.