Django限制查询 [英] Django limit query

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

问题描述

我正在尝试运行Django查询,该查询会将返回的结果限制为5个项目.这很容易,除了查询不会总是返回5个项目.在这种情况下,这样的语句(我的代码)将失败:

I am trying to run a Django query that will limit the returned results to 5 items. This is easy, except for the fact that the query will not always return 5 items. In that case, a statement like this (my code) fails:

 users = User.objects.filter(username__istartswith = name)[5].only('Person__profile_picture', 'username')

如果查询仅返回单个结果,则会出现索引超出范围错误.有没有一种方法可以指示Django给我最多5个结果而不会让我崩溃呢?是仅将所有内容包装在try块中的标准解决方案吗?还是我需要编写原始SQL查询来完成此任务?

If the query only returns a single result, I get an index out of range error. Is there a way to instruct Django to give me a maximum of 5 results without crashing on me? Is the standard solution to just wrap everything up in a try block? Or do I need to write a raw SQL query to accomplish this?

推荐答案

与doc中一样:例如,这将返回前5个对象(LIMIT 5):

For example, this returns the first 5 objects (LIMIT 5):

Entry.objects.all()[:5]

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

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