从 Django 的 raw() 查询函数获取结果数
我正在使用原始查询,但无法找出如何获取它返回的结果数。有办法吗?
编辑
.count() 不起作用。它返回:“RawQuerySet”对象没有属性“count”
I'm using a raw query and i'm having trouble finding out how to get the number of results it returns. Is there a way?
edit
.count() doesnt work. it returns: 'RawQuerySet' object has no attribute 'count'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以首先将其转换为列表以获取长度,如下所示:
如果您希望获得模板中 RawQuerySet 的长度甚至条目的存在性,则需要这样做。只需像上面那样预先计算长度,并将其作为参数传递给模板即可。
You can also cast it first to a list to get the length, like so:
This is needed if you want to have the length or even the existence of entries in the RawQuerySet in templates as well. Just precalculate the length like above, and pass it as a parameter to the template.
我认为您正在谈论raw()
queryset 方法。与其他查询集一样,它会返回一个查询集。因此,您当然可以对其调用.count()
,就像调用任何其他 ORM 查询一样。Edit 显示当您不这样做时会发生什么查看。正如您所注意到的,
.raw()
返回一个没有 count 方法的 RawQuerySet - 并且它也不支持len()
。获取长度的唯一方法是迭代查询集并对它们进行计数:I presume you're talking about theraw()
queryset method. That returns a queryset just like any other. So of course you can call.count()
on it, just like you would on any other ORM query.Edit Shows what happens when you don't check. As you note,
.raw()
returns a RawQuerySet which doesn't have a count method - and neither does it supportlen()
. The only way to get the length is to iterate through the queryset and count them:Count 适用于 RawQuerySet
Count Works on RawQuerySet