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.
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.
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.
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.
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)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With