Skip to content

Commit dba9493

Browse files
authored
Don't evaluate default_timezone unless needed (#8531)
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.
1 parent fa9d516 commit dba9493

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

rest_framework/fields.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1179,7 +1179,7 @@ def enforce_timezone(self, value):
11791179
When `self.default_timezone` is `None`, always return naive datetimes.
11801180
When `self.default_timezone` is not `None`, always return aware datetimes.
11811181
"""
1182-
field_timezone = getattr(self, 'timezone', self.default_timezone())
1182+
field_timezone = self.timezone if hasattr(self, 'timezone') else self.default_timezone()
11831183

11841184
if field_timezone is not None:
11851185
if timezone.is_aware(value):

0 commit comments

Comments
 (0)