Get the index of an element in a queryset

后端 未结 6 827
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  天涯浪人
    2020-12-04 18:23

    Assuming for the purpose of illustration that your models are standard with a primary key id, then evaluating

    list(qs.values_list('id', flat=True)).index(obj.id)
    

    will find the index of obj in qs. While the use of list evaluates the queryset, it evaluates not the original queryset but a derived queryset. This evaluation runs a SQL query to get the id fields only, not wasting time fetching other fields.

提交回复
热议问题