The Python Oracle

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

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

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Question
01:52 Accepted answer (Score 41)
02:31 Thank you

--

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

Accepted answer links:
[SerializerMethodField]: https://www.django-rest-framework.org/ap...

--

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