Get the index of an element in a queryset

后端 未结 6 816
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 18:08

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

6条回答
  •  萌比男神i
    2020-12-04 18:26

    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.

    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.

提交回复
热议问题