简体   繁体   中英

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 ex 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.

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/

You can extend or customize pagination classes available in drf

  class UserSpecificPagination(LimitOffsetPagination):
      def get_limit(self, request):
          if logic_met(request.user):
            self.max_limit = custom_limit
      return super(UserSpecificPagination, self).get_limit(request)

set the class as pagination_class in ListAPIView or DRF settings

you should use the pagination api from django-rest

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

look at the limit option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM