I am attempting to implement a nested resource where one of its fields depends on a value from its parent resource.
Suppose we are building a system for a company which
Moment of clarity: the solution is to use a SerializerMethodField
to instantiate the RepSummarySerializer
and pass the customer_id
in the context:
class CustomerSummarySerializer(serializers.HyperlinkedModelSerializer):
id = ...
name = ...
rep = serializers.SerializerMethodField('get_rep')
def get_rep(self, obj):
rep = obj.rep
serializer_context = {'request': self.context.get('request'),
'customer_id': obj.id}
serializer = RepSummarySerializer(rep, context=serializer_context)
return serializer.data
The customer_id
can now be accessed in RepSummarySerializer.get_rep_url
like this:
def get_rep_url(self, obj):
customer_id = self.context.get('customer_id')
...
Don't know why I didn't think of this three hours ago.