[Django]-Django query ordered objects given position

4👍

You can find the position of the object with a simple count query – something like this:

object_1 = Object.objects.get(pk=id)

# Count how many items have more votes than this one
# This effectively tells you the position in your ordered list 
position = Object.objects.filter(votes__gt=object_1.votes).count()

# Now generate your list of nearby objects
objects = Object.objects.order_by('-votes')[position-4:position+2]

(Note: this example would need to be tweaked for position < 4. You’d also need some logic to ensure deterministic ordering in cases where objects have the same number of votes.)

Leave a comment