【发布时间】:2017-01-03 01:11:07
【问题描述】:
我有一个 redis 排序集,其中包含对象 ID 及其各自的排序分数。我需要检索这些对象的 Django 查询集,根据排序集的分数进行排序。最有效的方法是什么?我的数据库是 postgresql。
目前,我正在分别检索 redis 排序集和 未排序 查询集。接下来,我根据排序集在 python 中的分数对查询集进行排序。可以在这里有意义地削减步骤,例如以某种方式在检索点对查询集进行排序等?
obj_ids_with_scr = get_ids_w_scr() #retrieves redis sorted set with scores
obj_ids = map(itemgetter(0),obj_ids_with_scr) # filters sorted set for just the obj ids
queryset = Widget.objects.filter(id__in=obj_ids) #unsorted queryset
a = dict(obj_ids_with_scr) #turning the sorted set into a dictionary
for obj_pk, sort_score in a:
obj = queryset.get(id=obj_pk) #get object with id equalling obj_pk
sort_score = obj #assign the object to the 'score' value of this key-value
result = a.values() #making a list of all values, that are now in sorted order
return result
【问题讨论】:
-
你用的是什么数据库?
-
我使用的是 postgresql 9.3
标签: python django sorting redis