2017-08-15 42 views
1

我有點在心裏卡住的東西,這似乎很簡單乍一看。訂購基於其他列表的ID和分數的Django查詢集

我在抓取要選擇的ids的列表,並根據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) 

到目前爲止好 - 但我該如何將分數添加爲某種聚合,並根據它們對查詢集進行排序?

回答

2

排序分數列表,並使用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] 
+0

謝謝!非常感激! 因爲我有一個select_related,我沒有提到使用'in_bulk' –