The Python Oracle

How can I serialize a queryset from an unrelated model as a nested serializer?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping

--

Chapters
00:00 How Can I Serialize A Queryset From An Unrelated Model As A Nested Serializer?
01:34 Accepted Answer Score 45
02:01 Thank you

--

Full question
https://stackoverflow.com/questions/4277...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #postgresql #serialization #djangorestframework

#avk47



ACCEPTED ANSWER

Score 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