1👍
✅
Here are two ways of achieving that:
- You can use a
SerializerMethodField
to access theself.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')
- You can override the
__init__
method of yourThreadViewSerializer
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')
Source:stackexchange.com