Get the index of an element in a queryset

后端 未结 6 817
佛祖请我去吃肉
佛祖请我去吃肉 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:40

    You can do this using queryset.extra(…) and some raw SQL like so:

    queryset = queryset.order_by("id")
    record500 = queryset[500]
    
    numbered_qs = queryset.extra(select={
        'queryset_row_number': 'ROW_NUMBER() OVER (ORDER BY "id")'
    })
    
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute(
        "WITH OrderedQueryset AS (" + str(numbered_qs.query) + ") "
        "SELECT queryset_row_number FROM OrderedQueryset WHERE id = %s",
        [record500.id]
        )
    index = cursor.fetchall()[0][0]
    
    index == 501 # because row_number() is 1 indexed not 0 indexed
    

提交回复
热议问题