根据其他具有ID和分数的列表订购Django查询集 [英] 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.
我要获取要选择的 ids
列表和 scores
对其进行排序的列表.
I'm grabbing a list of ids
to be selected and scores
to sort them based on.
我当前的解决方法如下:
My current solution is the following:
ids = [1, 2, 3, 4, 5]
items = Item.objects.filter(pk__in=ids)
现在,我需要以某种方式添加基于分数的排序,因此,我将建立以下列表:
Now I need to add a score based ordering somehow so I'll build the following list:
scores = [
{'id': 1, 'score': 15},
{'id': 2, 'score': 7},
{'id': 3, 'score': 17},
{'id': 4, 'score': 11},
{'id': 5, 'score': 9},
]
ids = [score['id'] for score in scores]
items = Item.objects.filter(pk__in=ids)
到目前为止还不错-但是我如何实际将分数添加为某种汇总,并根据分数对查询集进行排序?
So far so good - but how do I actually add the scores as some sort of aggregate and sort the queryset based on them?
推荐答案
对得分列表进行排序,并使用 in_bulk()
获取查询集.
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 order
ids = [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]
这篇关于根据其他具有ID和分数的列表订购Django查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!