How do I get the position of a result in the list after an order_by?
Posted
by Bob Bob
on Stack Overflow
See other posts from Stack Overflow
or by Bob Bob
Published on 2010-04-17T17:09:34Z
Indexed on
2010/04/17
17:13 UTC
Read the original article
Hit count: 306
I'm trying to find an efficient way to find the rank of an object in the database related to it's score. My naive solution looks like this:
rank = 0
for q in Model.objects.all().order_by('score'):
if q.name == 'searching_for_this'
return rank
rank += 1
It should be possible to get the database to do the filtering, using order_by:
Model.objects.all().order_by('score').filter(name='searching_for_this')
But there doesn't seem to be a way to retrieve the index for the order_by step after the filter.
Is there a better way to do this? (Using python/django and/or raw SQL.)
My next thought is to pre-compute ranks on insert but that seems messy.
© Stack Overflow or respective owner