简体   繁体   中英

How to serialize mutiple querysets in django rest framework?

I have two models that area related to each other. One represents a project and the other one represents the field/area that the project bnelongs to.

I have a view that looks like this:

class ProjetosArea(generics.ListAPIView):
    lookup_field = 'id'
    serializer_class = ProjetosPreviaSerializer
    pagination_class = ProjectPagination

    def get_queryset(self):
        area_id = self.kwargs['id']

        area = AreaConhecimento.objects.get(id=area_id)
        projetos = Projeto.objects.filter(area_conhecimento=area_id)

        queryset =  [area, projetos]

        return queryset

I want to write a serializer for this view that looks like this:

{
   "area": {---fields of the area---},
   "projects": [---The projects that belongs to that area---]
}

How would write a serializer for this? The queryset is a list with the area and the projects belonging to that area

This get_queryset doesn't look right. The idea is to return a single queryset there to perform permissions check etc in there. You should not return two resources like that.

Although if you need it - the code is just a tool. Do with it whatever you need.


I'd suggest to keep get_queryset as it is and overwrite list method instead as that's what you really want to do. Because you are returning two resources, it needs to know how to handle them.

From example I deduct that area_conhecimento is area pk . So something like that should work.

class ProjetosArea(generics.ListAPIView):
    lookup_field = 'area_conhecimento'
    serializer_class = ProjetosAreaSerializer
    pagination_class = ProjectPagination

    def list(self, request, *args, **kwargs):
        qs = self.filter_queryset(self.get_queryset())

        area = qs.first().area_conhecimento

        # you will have to adjust it for pagination
        serializer = self.get_serializer({
            'projects': qs,
            'area': area
        })
        return Response(serializer.data)

And just the serializers are as simple as it gets.

from rest_framework import serializers


class AreaConhecimentoSerializer(serializers.ModelSerializer):
    class Meta:
        model = AreaConhecimento
        fields = '__all__'


class ProjetoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Projeto
        fields = '__all__'


class ProjetosAreaSerializer(serializers.Serializer):
    area = AreaConhecimentoSerializer(read_only=True)
    projects = ProjetoSerializer(many=True, read_only=True)


But your real problem is that you actually want to get area and its projects. So just do it. You said it yourself The projects that belongs to that area .

class AreaRetrieveAPIView(RetrieveAPIView):
    serializer_class = AreaSerializer
    pagination_class = AreaPagination


class ProjetoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Projeto
        fields = '__all__'
        

class AreaSerializer(serializers.ModelSerializer):
    projeto = ProjetoSerializer(many=True, read_only=True)
    
    class Meta:
        model = AreaConhecimento
        fields = '__all__'

and it will return

{
   "area": {
        "projects": [---The projects that belongs to that area---],
         ---fields of the area---
    },
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM