(Please let me know if this is completely absurd, that is probably a reason why I haven't found anything on this.)
This story has two models Ranking
and Artist
, Ranking
is generically related to Artist
(object_id, content_type... the whole shebang).
I have a list of objects returned by Ranking.objects.values_list()
ordered by a certain field (in my case score
). So obviously, if I want to display a list of artists that were ranked, I'd want them in the same order. I've tried different methods, such as .filter(pk__in=list)
, .in_bulk(list)
, etc. Tried coercing the result of .values_list()
into a tuple too.
They all take my list:
>>> objects = Ranking.objects.filter(<stuff>).order_by('score')
>>> objects_list = objects.values_list('object_id', flat=True)
>>> objects_list
[8, 1, 2, 15, 14, 3, 13, 31, 16, 5, 4, 7, 32, 9, 37]
And return it like so:
>>> Artist.objects.filter(id__in=objects_list).values_list('id', flat=True)
[7, 32, 3, 8, 4, 2, 31, 9, 37, 13, 16, 1, 5, 15, 14]
(I'm just giving the IDs in the second case for sanity's sake.)
Right now the only way I can get this to work is to create an empty list and loop through the non-values_list()
query.
for item in objects:
ranked_items.append(item.content_object)
This just produces n
queries, so I'm wondering if there's a better way. As shown by the tags, I'm using PostgreSQL.