[英]How to limit query results with Django Rest filters
I am working on an api built with Django Rest Framework
.我正在研究使用
Django Rest Framework
构建的 api。 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
.我已经定义了几个
model
类,我还创建了一些过滤器来应用在指定的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]
.我想在申请LIMIT
queryset
,但我宁愿不使用Django的符号前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.我想我应该找到一种方法来定义具有默认值的过滤器,这会导致不限制查询集,并且如果请求到达端点并包含诸如
?filter=10
则查询集应限制为前 10 个.
You can use Django Rest Framework pagination.您可以使用 Django Rest Framework 分页。 The pagination_class
LimitOffsetPagination
give you the ability to limit the number of returned entries in a query_param. pagination_class
LimitOffsetPagination
使您能够限制 query_param 中返回条目的数量。
http://www.django-rest-framework.org/api-guide/pagination/ http://www.django-rest-framework.org/api-guide/pagination/
You can extend or customize pagination classes available in drf您可以扩展或自定义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在
ListAPIView
或 DRF 设置中将类设置为pagination_class
you should use the pagination api from django-rest您应该使用 django-rest 中的分页 API
http://www.django-rest-framework.org/api-guide/pagination/ http://www.django-rest-framework.org/api-guide/pagination/
look at the limit
option查看
limit
选项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.