Ordering A Django Queryset Based On Other List With Ids And Scores
I'm a bit mentally stuck at something, that seems really simple at first glance. I'm grabbing a list of ids to be selected and scores to sort them based on. My current solution is
Solution 1:
Sort the scores list, and fetch the queryset using in_bulk()
.
scores = [
{'id': 1, 'score': 15},
{'id': 2, 'score': 7},
{'id': 3, 'score': 17},
{'id': 4, 'score': 11},
{'id': 5, 'score': 9},
]
sorted_scores = sorted(scores) # use reverse=True for descending orderids = [score['id'] for score in scores]
items = Item.objects.in_bulk(ids)
Then generate a list of the items in the order you want:
items_in_order = [items[x] for x in ids]
Post a Comment for "Ordering A Django Queryset Based On Other List With Ids And Scores"