Return results from multiple models with Django REST Framework

前端 未结 1 591
不思量自难忘°
不思量自难忘° 2020-12-12 19:08

I have three models — articles, authors and tweets. I\'m ultimately needing to use Django REST Framework to construct a feed that aggregates all the objects using the Articl

相关标签:
1条回答
  • 2020-12-12 19:54

    It looks pretty close to me. I haven't used ViewSets in DRF personally, but I think if you change your code to this you should get somewhere (sorry - not tested either of these):

    class TimelineViewSet(viewsets.ModelViewSet):
        """
        API endpoint that lists all tweet/article objects in rev-chrono.
        """
        def list(self, request):
            queryset = list(itertools.chain(Tweet.objects.all(), Article.objects.all()))
            serializer = TimelineSerializer(queryset, many=True)
            return Response(serializer.data)
    

    If you're not wedded to using a ViewSet then a generics.ListAPIView would be a little simpler:

    class TimeLineList(generics.ListAPIView):
        serializer_class = TimeLineSerializer
    
        def get_queryset(self):
            return list(itertools.chain(Tweet.objects.all(), Article.objects.all()))
    

    Note you have to convert the output of chain to a list for this to work.

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