How to pass request object from one serializer class to other serializer class in Django

Issue

I want to access userId of current logged-in user. for that i need to pass the request object from one serialiser to another. Here’s my code

class ThreadViewSerializer(serializers.ModelSerializer):
op = PostDetailViewSerializer(context={'request': request})

class Meta:
    model = Thread
    fields = ('id', 'title', 'op', 'group_id', 'type', 'reference_id', 'is_frozen', 'views', 'is_pinned')

In PostDetailViewSerializer, I want to pass request object but for that it requires self object. like this

request = self.context.get('request')

Thus, How can we pass the request object to PostDetailViewSerializer class in ThreadViewSerializer class. Please help me in this.

Solution

Here are two ways of achieving that:

  1. You can use a SerializerMethodField to access the self.context (keep in mind that this a read-only serializer):
class ThreadViewSerializer(serializers.ModelSerializer):
    op = serializers.SerializerMethodField()

    def get_op(self, instance):
        return PostDetailViewSerializer(instance=instance.op, context=self.context).data

    class Meta:
        model = Thread
        fields = ('id', 'title', 'op', 'group_id', 'type', 'reference_id', 'is_frozen', 'views', 'is_pinned')
  1. You can override the __init__ method of your ThreadViewSerializer and pass the context then down to your fields:
class ThreadViewSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['op'] = PostDetailViewSerializer(context=self.context)

    class Meta:
        model = Thread
        fields = ('id', 'title', 'op', 'group_id', 'type', 'reference_id', 'is_frozen', 'views', 'is_pinned')

Answered By – henriquesalvaro

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published