How to limit query results with Django Rest filters

LetsPlayYahtzee picture LetsPlayYahtzee · Nov 3, 2015 · Viewed 13.8k times · Source

I am working on an api built with Django Rest Framework. I have defined several model classes and I have also created some filters to apply on certain queries that happen in the specified api-endpoints.

I am trying to apply LIMIT in the queryset but I would prefer to not use the Django notation e.x. Entry.objects.all()[:5]. Instead I would like to be able to apply the limit from inside the filter associated with the model.

Until now I haven't find any solution. I am thinking that I should find a way to define a filter with default value something that would result in not limiting the queryset and if a request reaches the endpoint and contains something like ?filter=10 then the queryset should be limited to the first 10.

Answer

Guillaume Pannatier picture Guillaume Pannatier · Nov 3, 2015

You can use Django Rest Framework pagination. The pagination_class LimitOffsetPagination give you the ability to limit the number of returned entries in a query_param.

http://www.django-rest-framework.org/api-guide/pagination/