获取查询集中元素的索引 [英] Get the index of an element in a queryset

查看:23
本文介绍了获取查询集中元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QuerySet,我们称它为 qs,它由与此问题无关的某个属性排序.然后我有一个对象,我们称之为obj.现在我想知道 objqs 中有什么索引,尽可能高效.我知道我可以使用 Python 中的 .index() 或者可能通过 qs 循环比较每个对象与 obj,但最好的方法是什么去做这件事?我正在寻找高性能,这是我唯一的标准.

I have a QuerySet, let's call it qs, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it obj. Now I'd like to know at what index obj has in qs, as efficiently as possible. I know that I could use .index() from Python or possibly loop through qs comparing each object to obj, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.

在 Windows 上使用 Python 2.6.2 和 Django 1.0.2.

Using Python 2.6.2 with Django 1.0.2 on Windows.

推荐答案

Django 中的 QuerySets 实际上是生成器,而不是列表(更多详细信息,请参见 关于 QuerySets 的 Django 文档).
因此,获取元素索引没有捷径,我认为简单的迭代是最好的方法.

QuerySets in Django are actually generators, not lists (for further details, see Django documentation on QuerySets).
As such, there is no shortcut to get the index of an element, and I think a plain iteration is the best way to do it.

首先,我会以最简单的方式(如迭代)实现您的需求;如果你真的有性能问题,那么我会使用一些不同的方法,比如构建一个包含少量字段的查询集,或者其他什么.
无论如何,我们的想法是在您确定需要它们时尽可能晚地留下这些技巧.
更新:您可能想直接使用一些 SQL 语句来获取行号(有些谎言.但是,Django 的 ORM 本身不支持此功能,您必须使用原始 SQL 查询(请参阅 文档.我认为这可能是最好的选择,但同样 - 只有当您真的看到真正的性能问题时.

For starter, I would implement your requirement in the simplest way possible (like iterating); if you really have performance issues, then I would use some different approach, like building a queryset with a smaller amount of fields, or whatever.
In any case, the idea is to leave such tricks as late as possible, when you definitely knows you need them.
Update: You may want to use directly some SQL statement to get the rownumber (something lie . However, Django's ORM does not support this natively and you have to use a raw SQL query (see documentation). I think this could be the best option, but again - only if you really see a real performance issue.

这篇关于获取查询集中元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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