How to limit query results with Django Rest filters

戏子无情 提交于 2020-05-25 12:20:28

问题


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.


回答1:


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/




回答2:


you should use the pagination api from django-rest

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

look at the limit option




回答3:


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



来源:https://stackoverflow.com/questions/33503909/how-to-limit-query-results-with-django-rest-filters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!