[Answered ]-How to pass request object from one serializer class to other serializer class in Django

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

Leave a comment