27
loading...
This website collects cookies to deliver better user experience
class Venue(models.Model):
time_zone = models.CharField(max_length=128, default='UTC')
...
class Event(models.Model):
start_time = models.DateTimeField()
end_time = models.DateTimeField()
venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
...
default_timezone
, this is a pytz.timezone
representing the timezone. If not specified and the USE_TZ
setting is enabled, this defaults to the current timezone. If USE_TZ
is disabled, then datetime objects will be naive.class EventSerializer(serializers.ModelSerializer):
start_time = serializers.DateTimeField(default_timezone=pytz.timezone('America/Bogota'))
end_time = serializers.DateTimeField(default_timezone=pytz.timezone('America/Bogota'))
...
start_time
in UTC is 2021-09-02T10:00:00
in the resultant JSON will be displayed as 2021-09-02T05:00:00-05:00
. But it didn't just work for me because I don't know the time zones beforehand and also they will be different, so I needed to do this at runtime, my solution was to override the to_representation()
method from the serializer.class EventSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
self.fields['start_time'] = serializers.DateTimeField(default_timezone=pytz.timezone(instance.venue.time_zone))
self.fields['end_time'] = serializers.DateTimeField(default_timezone=pytz.timezone(instance.venue.time_zone))
return super().to_representation(instance)
...
to_representation
is run for each instance that is going to be returned by the serializer, so basically what we are doing is overriding the start_time
and end_time
declaration for each instance, this is for specifying that we want to use a DateTimeField
and we want to pass it a default_timezone
which is going to be taken from the venue that is linked to the instance.