问题
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