DRF: How to access "context" inside custom DecimalField class?

Viewed 143

I am subclassing the DecimalField class from Django RestFramework and need to access context. Formatting for decimal fields includes settings that are user-selectable, so I need to access the user object (which, I assume, should be inside context) inside the to_representation() method.

Via debug, I've looked at all properties of self inside my CustomDecimalField class, but, of course, I can't see class methods, so I don't know if there's an appropriate "get" method to get context. I've tried self.context (as a property), self.get_context(), and self.getcontext(), but none worked.

I found this announcement re: require_context: https://www.django-rest-framework.org/community/3.11-announcement/ ...but it seems to be valid only for validation and default value methods.

This seems like such a simple thing; hard to believe it is so difficult.

1 Answers

You have to manually set the user inside the context. So, in your view:

serializer = YourSerializer(your_data, context={'user': request.user})

And you will then be able to access it in your to_representation() method:

def to_representation(self, instance):
    user = self.context.get("user")

Please see the documentation for more information.

Related