Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query ordered objects given position

I have a function which takes an object id. With this id I can get the object of a table object_1 = Object.objects.get(pk=id). I'd like to have the Object table ordered by a position called votes. For example, objects = Object.objects.order_by('-votes') and I'd like to find the position of object_1 in objects.

How could I achieve that? As far as I know the Query Set is not a list, and I'd have to iterate over all elements, which would be a big performance issue when I have a lot of entries in the table.

The purpouse of all this is to show a ranking ordered by votes, in which I only show 6 entries and the 4th one should be the one of the object. For example if I searched for the object 1, I should show this:

Position | Name | Votes
   5      obj5     52
   6      obj3     49
   7      obj10    49
   8      obj1     47
   9      obj15    15
   10     obj6     14

So I'd like to get a query set with obj5,obj3,obj10,obj1,obj15,obj6 in this order. The optimal solution would be doing something like: objects = Object.objects.order_by('-votes')[x-4:x+2] where x is the position of the object I'm searching.

p.s: I'm using Python 2.7.9 and Django 1.9

like image 498
lpares12 Avatar asked Dec 28 '25 20:12

lpares12


1 Answers

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.)

like image 122
solarissmoke Avatar answered Dec 31 '25 10:12

solarissmoke