我们如何在覆盖 get_queryset() 方法的同时在单个 generics.ListAPIView 中使用两个不同的序列化程序

How can we use two different serializers in a single generics.ListAPIView while overriding get_queryset() method

我的Views.py

class RelatedFacultyProfile(generics.ListAPIView):
    serializer_class = FacultyProfileGenericSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        helper = UserTypeHelper(self.request, path=False)
        if helper.user_type == 'F':
            queryset = Faculty.objects.filter(department=self.request.user.faculty.department)
        if helper.user_type == 'S':
            queryset = Faculty.objects.filter(department=self.request.user.student.branch)        
        return queryset


class RelatedStudentProfile(generics.ListAPIView):
    serializer_class = StudentProfileGenericSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        helper = UserTypeHelper(self.request, path=False)
        if helper.user_type == 'F':
            queryset = Student.objects.filter(branch=self.request.user.faculty.department)
        if helper.user_type == 'S':
            queryset = Student.objects.filter(branch=self.request.user.student.branch)        
        return queryset

我想结合这两个视图的查询集来生成一个 JSON 响应,这将需要两个不同的序列化程序 那么如何实现呢?

您应该尝试使用 DjangoRestMultipleModels 包。专供您使用ObjectMultipleModelAPIView将是正确的选择。它具有分页的额外好处,因此您在查询查询集时可以获得性能优势。

此外,像这样覆盖 get_querylist() 函数

def get_querylist(self):
    helper = UserTypeHelper(self.request, path=False)
    if helper.user_type == 'F':
        querylist = [{'queryset': Faculty.objects.filter(department=self.request.user.faculty.department), 'serializer_class': FacultyProfileGenericSerializer},
                    {'queryset': Student.objects.filter(branch=self.request.user.faculty.department), 'serializer_class': StudentProfileGenericSerializer}]
    if helper.user_type == 'S':
        querylist = [{'queryset': Faculty.objects.filter(department=self.request.user.student.branch)), 'serializer_class': FacultyProfileGenericSerializer},
                    {'queryset': Student.objects.filter(branch=self.request.user.student.branch), 'serializer_class': StudentProfileGenericSerializer}]
    
    return querylist