How to get custom list view in django-rest-framework view

I have a tv channel model and created a django-restframework viewlet that gives me a list and a detailed view from the box. At the top, I added two custom views of the same object, called all_events and now_and_next_event, as described here: Marking additional methods for routing . It 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:

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

When I turn off my viewport and add a manual url template for it, it also works. But I did not understand how to make them work with the same prefix "api / channel /", or the fact that I would like to get more, how to add a custom list class to my window.

Here are my urlletle 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, for example:

 ^api/channel/current_events/$ [name='event-current'] 
+8
django django-rest-framework
source share
2 answers

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

From the documentation

The @detail_route decorator contains pk in the URL pattern and is intended for methods requiring a single instance. The @list_route decorator is for methods that work with a list of objects.

They replace the old @link and @action , which could only work as verbose routes.

+5
source share

If you need a list of objects, then you need a list method in ListApiView: For example, the ModelName model and classizer are SerializerClassname, then the code will be:

 class ExampleView(ListAPIView): model = ModelNmae serializer_class = SerializerClassName permission_classes = (IsAuthenticated,) def get_queryset(self): """ """ queryset = ModelName.objects.all() q = self.request.query_params.get('q', None) if q is not None: queryset =queryset.filter(name__icontains=q) return queryset def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) result = [ x.values()[0] for x in serializer.data ] return Response(result) 
+1
source share

All Articles