Get Request Object in Django Rest Framework Serializer

I have a problem when getting session information inside my serializer method field that I had

class PersonSerializer(serializers.ModelSerializer):
    role = serializers.SerializerMethodField()

    def get_role(self, obj):
        # I have to get session in here.
        pass

    class Meta:
        model = Person

First time we need to do is, get request object in our method, then we can get our session information on it.

def get_role(self, obj):
    # Get request object.
    request = self.context.get('request')
    
    # Get session information.
    session_information = request.session.get('my_session')

Reference: http://stackoverflow.com/a/27832803/1936697

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s