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.

    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')


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.