Django.rest_framework: How to serialize one to many to many?

前端 未结 1 1782
孤街浪徒
孤街浪徒 2021-02-02 17:06

I have some troubles serializing with django. I have three models, let\'s say a School, a Room and a Desk (dummy name for example). Each School have multiple Room, and each Room

相关标签:
1条回答
  • 2021-02-02 17:40

    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.

    0 讨论(0)
提交回复
热议问题