DRF-嵌套反向关系序列化器

时间:2019-11-09 18:13:56

标签: django django-rest-framework

如何创建具有所有反向关系的family返回所有结果的序列化程序?

         Family
           |
    +------+------+
    |             |
 Student    EmergencyContact
    |
   Fee

例如

{family: [{id: 1,
          student_set: [{id: 1, name: "bob Jones", fee_set: [{"Maths Fee": 3,  "English Fee": 5}}],
                        {id: 2, name: "Mike Jones", fee_set: [{"English Fee": 5}}],
          emergency_contact_set: [{id: 1, name:"Joe"}, {id: 2, name: "Mike"}]
         ]
}

我可以在字段中使用<model>_set来获得单个嵌套数据级别,例如student_set, emergency_contact_set,但不是深层嵌套(fee_set)。

class FamilySerializer(serializers.ModelSerializer):
    student = StudentSerializer(many=True, read_only=True)  # does nothing
    class Meta:
          model = Family
          fields = ["id",
                    "name", 
                    "student", # returns nothing
                    "student_set" # only returns the students WITHOUT the fees
                   ]

输出(没有fees):

{family: [{id: 1,
          student_set: [{id: 1, name: "bob Jones"}],
                        {id: 2, name: "Mike Jones"}],
          emergency_contact_set: [{id: 1, name:"Joe"}, {id: 2, name: "Mike"}],
         ]
}

理想情况下,我想在StudentSerializer中使用EmergencyContactSerializerFamily来获取嵌套集。

1 个答案:

答案 0 :(得分:0)

您必须在#include <stdio.h> #define MAX 5 int my_sum_array(const int a[], int n); int main(void) { int values[5] = {4, 7, 1, 7, 8}; printf("The sum in my_sum_array is :%d\n", my_sum_array(values, MAX)); return 0; } int my_sum_array(const int a[], int n) { int *p, sum = 0; for (p = a; p < a + n; p++) sum += *p; return sum; } 中使用source kwarg,例如XXXXSerializer(或在模型中重命名source="<field>_set",并将其用作related_field)。

source

class FamilySerializer(serializers.ModelSerializer): student = StudentSerializer(many=True, read_only=True, source="student_set") ... class Meta: ... 字段将student可用

请参阅: https://riptutorial.com/django-rest-framework/example/30725/getting-list-of-all-related-children-objects-in-parent-s-serializer