Last active
March 20, 2024 12:06
-
-
Save gauravvjn/deb0c3fdfc216515e30f50d58dc49e1d to your computer and use it in GitHub Desktop.
Make Django model's DateTime fields timezone aware by calling this function in models class. Django doesn't automatically make those fields timezone aware, especially the auto_now and auto_now_add ones. This method will make ALL DateTime fields in the model timezone aware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.utils import timezone | |
import pytz | |
class ModelMixin: | |
def make_datetime_fields_value_timezone_aware(self): | |
# HACK: Monkey patching to fix TypeError for existing data in DB | |
# TypeError: can't compare offset-naive and offset-aware datetimes | |
utc_tz = pytz.timezone(settings.TIME_ZONE) | |
for field in self._meta.get_fields(): | |
if field.get_internal_type() == "DateTimeField": | |
field_name = field.name | |
field_value = getattr(self, field_name, None) | |
if field_value and not timezone.is_aware(field_value): | |
setattr(self, field_name, timezone.make_aware(field_value, utc_tz)) | |
# And use it in model class like below. | |
class MyModel(ModelMixin, models.Model): | |
# model fields ... | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.make_datetime_fields_value_timezone_aware() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment