Last active
April 15, 2021 19:24
-
-
Save miljkovicivan/ab6efd22a423000e4ca18adff614f327 to your computer and use it in GitHub Desktop.
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
class Profile(models.Model): | |
start_datetime = models.DateTimeField() | |
some_timezone = models.CharField() |
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
import pytz | |
class CustomDateTimeField(serializers.DateTimeField): | |
def get_attribute(self, instance): | |
# Save instance here for later usage | |
self.instance = instance | |
return super().get_attribute(instance) | |
def to_representation(self, value): | |
# how to access single `instance` here? | |
# the only "instance" I can access here is `self.root.instance` which is queryset in case of many=True | |
# If this is a single isntance serializer `self.root.isntance` is fine | |
# If this is a many=True serializer nothing makes sense | |
# This doesn't work | |
instance = self.root.instance | |
# This does work | |
instance = self.instance | |
value = pytz.timezone(instance.some_timezone).normalize(value) | |
return super().to_representation(value) | |
class ProfileSerializer(serializers.ModelSerializer): | |
start_datetime = CustomDateTimeField() | |
class Meta: | |
model = models.Profile | |
fields = ('start_date',) |
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
# This works | |
ProfileSerializer(Profile.objects.first()).data | |
# This doesn't work | |
# Error is: AttributeError: 'Manager' object has no attribute 'some_timezone' | |
ProfileSerializer(Profile.objects.all(), many=True).data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment