[Fixed]-Accessing Request Object in Viewset and Serializers in Django Rest Framework?

37👍

You don’t need to include request object in the context as the generic views passes request object to the serializer context.

DRF Source code snippet:

# rest_framework/generics.py
def get_serializer_context(self):
    """
    Extra context provided to the serializer class.
    """
    return {
        'request': self.request, # request object is passed here
        'format': self.format_kwarg,
        'view': self
    }

In your serializer, you can access the request object using .context attribute.

The context dictionary can be used within any serializer field logic,
such as a custom .to_representation() method, by accessing the
self.context attribute.

class ProductSerializer(serializers.HyperlinkedModelSerializer):

    get_sr_price = serializers.SerializerMethodField('get_sr_price_func')

    def get_sr_price_func(self, obj):
        return self.context['request'].user # access the request object

1👍

Serializers are the way external data is mapped from / to models (Django or simple Python classes).

Views are dealing with how the data will be shown. Throttling, pagination, authentication are managed by the view. They also handle the data set.

DRF provides a context to pass request specific data to the serializer without having to redefine the init. This is likely what you’re looking for.

Leave a comment