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

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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 henriquesalvaro