Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering ListAPIView in django-rest-framework

Tags:

I'm using ListAPIView, but I can't filter the results. My code is:

class UserPostReadView(generics.ListAPIView):     serializer_class = PostSerializer     model = serializer_class.Meta.model     queryset = model.objects.order_by('-post_time')     lookup_field = 'poster_id'     paginate_by = 100 

In this case, lookup_field is ignored, but the documentation says that it's supported for this class too. If I try to implement a custom get over a generic view, I don't know how to reimplement paginate_by. Any ideas?

like image 317
Francesco Frassinelli Avatar asked May 25 '13 19:05

Francesco Frassinelli


People also ask

What is Queryset in Django REST framework?

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.

What is filtering in Django?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this. Adding a FilterSet with filterset_class. Using the filterset_fields shortcut.


2 Answers

I've found the solution

class UserPostsReadView(generics.ListAPIView):     serializer_class = PostSerializer     model = serializer_class.Meta.model     paginate_by = 100     def get_queryset(self):         poster_id = self.kwargs['poster_id']         queryset = self.model.objects.filter(poster_id=poster_id)         return queryset.order_by('-post_time') 

Source: http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-url

like image 177
Francesco Frassinelli Avatar answered Sep 28 '22 06:09

Francesco Frassinelli


I know is late for this, but I wrote a little app that extends for ListAPIView and do this easier, check it out:

https://github.com/angvp/drf-lafv

like image 43
Angel Velásquez Avatar answered Sep 28 '22 06:09

Angel Velásquez