[Fixed]-Django.rest_framework: How to serialize one to many to many?

21👍

If I’m understanding you correctly, you want the SchoolSerializer to return a nested structure 2 levels deep, but skipping the intermediate model. To do this, I would create a method in your School model to retrieve the Desk instances:

class School(models.Model):
    ...

    def get_desks(self):
        rooms = Room.objects.filter(school=self)
        desks = Desk.objects.filter(room__in=rooms)
        return desks

Then, in your SchoolSerializer include a field that uses that method and renders the returned instances as you wish via your DeskSerializer:

class SchoolSerializer(serializers.ModelSerializer):
    ...
    desks = DeskSerializer(
        source='get_desks',
        read_only=True
    )

    class Meta:
        field = (name, desks)

The key to understanding how this works is that the model method used as the value for the source argument must simply return instances of that serializer’s model. The serializer takes it from there, rendering the object(s) however you defined them within that serializer (in this case the DeskSerializer).

Hope this helps.

👤Fiver

Leave a comment