From 417b9715b7ef35196ace470771a0d3d5ab3bc0c5 Mon Sep 17 00:00:00 2001 From: Stian Jensen Date: Wed, 22 Jun 2022 16:45:13 +0200 Subject: [PATCH] Don't evaluate default_timezone unless needed 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. --- rest_framework/fields.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 31e5b994c..45c8bbefd 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1179,7 +1179,7 @@ class DateTimeField(Field): 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):