Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit query results with Django Rest filters

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.

like image 541
LetsPlayYahtzee Avatar asked Nov 03 '15 16:11

LetsPlayYahtzee


People also ask

What is throttling in Django REST?

Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API. As with permissions, multiple throttles may be used.

Is Django GOOD FOR REST API?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.

How do you use DjangoFilterBackend?

To use DjangoFilterBackend , first install django-filter . Then add 'django_filters' to Django's INSTALLED_APPS : INSTALLED_APPS = [ ... 'django_filters', ... ] Or add the filter backend to an individual View or ViewSet.


2 Answers

In ListApiView Overwrite finalize_response function. I did not find any other inbuilt method or parameter to set limit on response data.

from rest_framework.generics import ListAPIView

class BoolQSearch(ListAPIView):
    queryset = Model1.objects.all()
    serializer_class = Model1Serializer

    def finalize_response(self, request, response, *args, **kwargs):
        response.data = response.data[:5]
        return super().finalize_response(request, response, *args, **kwargs)
like image 180
Aseem Avatar answered Oct 22 '22 05:10

Aseem


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/

like image 45
Guillaume Pannatier Avatar answered Oct 22 '22 07:10

Guillaume Pannatier