Skip to content

Instantly share code, notes, and snippets.

@miljkovicivan
Last active April 15, 2021 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miljkovicivan/ab6efd22a423000e4ca18adff614f327 to your computer and use it in GitHub Desktop.
Save miljkovicivan/ab6efd22a423000e4ca18adff614f327 to your computer and use it in GitHub Desktop.
class Profile(models.Model):
start_datetime = models.DateTimeField()
some_timezone = models.CharField()
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 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