使用 Django REST Framework 从多个模型返回结果 [英] Return results from multiple models with Django REST Framework

查看:36
本文介绍了使用 Django REST Framework 从多个模型返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个模型——文章、作者和推文.我最终需要使用 Django REST Framework 来构建一个提要,该提要将使用文章和推文模型的所有对象聚合到一个反向时间顺序提要中.

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 Article and Tweet models into one reverse chronological feed.

知道我该怎么做吗?我觉得我需要创建一个新的序列化程序,但我真的不确定.

Any idea how I'd do that? I get the feeling I need to create a new serializer, but I'm really not sure.

谢谢!

这是我迄今为止所做的.

Here's what I've done thus far.

app/serializers.py:

class TimelineSerializer(serializers.Serializer):
    pk = serializers.Field()
    title = serializers.CharField()
    author = serializers.RelatedField()
    pub_date = serializers.DateTimeField()

app/views.py:

class TimelineViewSet(viewsets.ModelViewSet):
    """
    API endpoint that lists all tweet/article objects in rev-chrono.
    """
    queryset = itertools.chain(Tweet.objects.all(), Article.objects.all())
    serializer_class = TimelineSerializer

推荐答案

它看起来很接近我.我个人没有在 DRF 中使用过 ViewSets,但我认为如果你把代码改成这样,你应该会有所收获(抱歉 - 没有测试过任何一个):

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)

如果您不习惯使用 ViewSet,那么 generics.ListAPIView 会更简单一些:

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()))

请注意,您必须将 chain 的输出转换为列表才能使其工作.

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

这篇关于使用 Django REST Framework 从多个模型返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆