45👍
✅
You can use DRF’s SerializerMethodField
.
Define your ResearchTemplateSerializer
as a normal ModelSerializer, not as a RelatedField
.
Then replace your ResearchSerializer
with this:
class ResearchSerializer(serializers.ModelSerializer):
templates = serializers.SerializerMethodField()
class Meta:
model = Research
fields = ('id', 'created', 'speaker', 'body', 'templates')
def get_templates(self, obj):
values = obj.get_values() # whatever your filter values are. obj is the Research instance
templates = ResearchTemplate.objects.filter(mergefields__contained_by=values) # Or whatever queryset filter
return ResearchTemplateSerializer(templates, many=True).data
Source:stackexchange.com