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

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

问题描述

我有一个QuerySet,让我们称之为 qs ,这是由与这个问题无关的某些属性排序的。然后我有一个对象,让我们称之为 obj 。现在我想知道在 qs 中的哪个索引 obj 有效 尽可能。我知道我可以使用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语句来获取这个rownumber(可以说是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天全站免登陆