【问题标题】:Ordering a Django queryset based on the sorting of a sorted set from redis根据来自 redis 的排序集的排序来排序 Django 查询集
【发布时间】:2016-11-30 19:46:34
【问题描述】:

我有一个来自 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 错误而失败 - 我仍在调试它。尽管如此,我也觉得可能有更快的方法来做我想做的事情,因此我问了这个问题。提前致谢!

【问题讨论】:

    标签: python django sorting redis


    【解决方案1】:

    将你的 for 循环替换为:

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

    如果 qs 中的任何内容不在 redis 结果中,这将出现异常 - 如果可能发生这种情况,请使用带有一些合理默认值的 dictionary.get(item.pk, ...) 而不是 dictionary[item.pk]。

    【讨论】:

    • 谢谢哥们,我会尽快回复你
    • 如果查询集中的某些 id不存在,但在 sorted_set 中存在怎么办?在这种情况下,lambda 函数将返回一个key,它在queryset 中不存在。结果会自动排除那些条目?
    • sorted 对第一个参数的元素进行排序 - 在本例中为 queryset。 key 只定义了如何计算第一个参数的每个元素的排序优先级,因此它将忽略排序集中但不在查询集中的元素。另一个可能更清楚地显示该行为的示例是按长度对字符串列表进行排序 - sorted(list_of_strings, key=len)。任何字符串都可以计算其长度,但只有初始列表中的字符串才会出现在排序结果中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    相关资源
    最近更新 更多