如何使用Django Rest过滤器限制查询结果 [英] How to limit query results with Django Rest filters

查看:231
本文介绍了如何使用Django Rest过滤器限制查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django Rest Framework 编写的api。我已经定义了几个模型类,我还创建了一些过滤器来应用于在指定的 api-endpoints

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.

我试图在 queryset 中申请LIMIT,但我宁愿不要
使用Django表示法 Entry.objects.all()[:5] 。相反,我希望能够从与模型相关联的过滤器中应用限制。

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.

到目前为止,我还没有找到任何解决方案。我想我应该找到一种方法来定义具有默认值的过滤器,这将导致不限制查询器,并且如果请求到达端点并包含类似于?filter = 10 那么查询器应该被限制在前10个。

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.

推荐答案

可以使用Django Rest Framework分页。 pagination_class LimitOffsetPagination 使您能够限制query_param中返回的条目数。

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/

这篇关于如何使用Django Rest过滤器限制查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆