gpt4 book ai didi

python - 根据带有 id 和分数的其他列表对 Django 查询集进行排序

转载 作者:行者123 更新时间:2023-12-01 02:41:18 24 4
gpt4 key购买 nike

我在精神上有点陷入困境,乍一看似乎很简单。

我正在获取要选择的 id 列表以及用于对它们进行排序的scores 列表。

我当前的解决方案如下:

ids = [1, 2, 3, 4, 5]

items = Item.objects.filter(pk__in=ids)

现在我需要以某种方式添加基于分数的排序,因此我将构建以下列表:

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)

到目前为止一切顺利 - 但我如何实际将分数添加为某种聚合并根据它们对查询集进行排序?

最佳答案

对分数列表进行排序,并使用 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)

然后按照您想要的顺序生成项目列表:

items_in_order = [items[x] for x in ids]

关于python - 根据带有 id 和分数的其他列表对 Django 查询集进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45693437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com