Search code examples
pythondjangodjango-rest-frameworkviewdjango-serializer

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


My 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

I want to combine the querysets of these two views to generate a single JSON response which will require two different serializers So how to achieve this ?


Solution

  • You should try using the DjangoRestMultipleModels package. Specifically for your use ObjectMultipleModelAPIView will be the right choice. It has the added benefit of pagination so you get performance benefits when querying the querysets.

    Also, override the get_querylist() function like so

    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