如何在Django-Rest-Framework ViewSet中获取自定义列表视图 [英] How to get custom list view in django-rest-framework viewset

查看:30
本文介绍了如何在Django-Rest-Framework ViewSet中获取自定义列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个电视频道模型,并创建了一个django-restframework视图,它为我提供了列表和详细视图.首先,我添加了两个自定义的单对象视图,分别称为all_events和now_and_next_event,如下所述:标记用于路由的其他方法.到目前为止效果很好.

I have a tv channel model and created a django-restframework viewlet which gives me a list and a detail view out of the box. On top I added two custom single-object views called all_events and now_and_next_event, as described here: Marking extra methods for routing. That works great so far.

class ChannelViewSet(viewsets.ModelViewSet):
    """
    A viewset for viewing and editing channel instances.
    """
    serializer_class = serializers.ChannelSerializer
    queryset = Channel.objects.all()

    @link()
    def now_and_next_event(self, request, pk):
        ''' Show current and next event of single channel. '''
        ...

现在,我想添加一个自定义视图,它不是单对象视图,而是类似列表的视图:

Now I would like to add a custom view which is NOT a single-object view but a list-like view:

class CurrentEvents(generics.ListCreateAPIView):
    ''' Show current event of all channels. '''
    model = Event
    serializer_class = serializers.EventSerializer

    def get(self, request):
        ...

当我禁用视口并为其添加手动url模式时,它也可以正常工作.但是我还没有弄清楚如何使它们都使用相同的"api/channel/"前缀,或者我还想知道如何将自定义列表视图类添加到我的视图中.

When I disable my viewlet and add a manual url pattern for it, it works as well. But I haven't figured out how to make them both work with the same 'api/channel/' prefix, or what I would like more, how to add the custom list view class into my viewlet.

这是我的viewlet网址格式:

Here are my viewlet url patterns:

^api/channel/$ [name='channel-list']
^api/channel/(?P<pk>[^/]+)/$ [name='channel-detail']
^api/channel/(?P<pk>[^/]+)/all_events/$ [name='channel-all-events']
^api/channel/(?P<pk>[^/]+)/now_and_next_event/$ [name='channel-now-and-next-event']

我想访问我的列表视图,例如:

And I would like to access my list view like:

^api/channel/current_events/$ [name='event-current']

推荐答案

从Django REST Framework 2.4开始,您现在可以使用 @list_route 装饰 ViewSet 方法以获取什么您正在寻找.

As of Django REST Framework 2.4, you can now decorate ViewSet methods with @list_route to get what you are looking for.

来自文档

@detail_route 装饰器在其URL模式中包含 pk ,适用于需要单个实例的方法. @list_route 装饰器旨在用于对对象列表进行操作的方法.

The @detail_route decorator contains pk in its URL pattern and is intended for methods which require a single instance. The @list_route decorator is intended for methods which operate on a list of objects.

这些替换了以前只能用作详细信息路线的 @link @action 装饰器.

These replace the old @link and @action decorators which were only able to work as detail routes.

这篇关于如何在Django-Rest-Framework ViewSet中获取自定义列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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