gpt4 book ai didi

python - 根据来自 redis 的排序集的排序排序 Django 查询集

转载 作者:IT王子 更新时间:2023-10-29 06:14:07 25 4
gpt4 key购买 nike

我有一个来自 Redis 的排序集。排序集包含对象的 ID 及其排序分数。

接下来,我有一个 Django 查询集,由其排序 ID 包含在上述 Redis 排序集中的对象组成。

我需要根据 ID 在 redis 排序集中 中的位置对这个 Django 查询集进行排序。最快的方法是什么?


我正在尝试以下操作:

    dictionary = dict(sorted_set) #turning the sorted set into a dictionary
for pk, score in dictionary:
obj = queryset.get(id=pk) #get object with id equalling pk
score = object #assign the object to the 'score' value of this key-value
result = dictionary.values() #making a list of all values, that are now in sorted order

上面的 for 循环因 too many values to unpack 错误而失败 - 我仍在调试它。尽管如此,我也觉得可能有更快的方法来做我想做的事情,因此我问了这个问题。提前致谢!

最佳答案

将您的 for 循环替换为:

result = sorted(queryset, key=lambda item: dictionary[item.pk], reverse=True)

如果 qs 中的任何内容不在 redis 结果中,这将出现异常 - 使用 dictionary.get(item.pk, ...) 和一些合理的默认值而不是 dictionary[ item.pk] 如果可以的话。

关于python - 根据来自 redis 的排序集的排序排序 Django 查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38602115/

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