Ordering a Django queryset based on other list with ids and scores

旧时模样 提交于 2021-02-10 17:49:54

问题


I'm a bit mentally stuck at something, that seems really simple at first glance.

I'm grabbing a list of ids to be selected and scores to sort them based on.

My current solution is the following:

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

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

Now I need to add a score based ordering somehow so I'll build the following list:

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)

So far so good - but how do I actually add the scores as some sort of aggregate and sort the queryset based on them?


回答1:


Sort the scores list, and fetch the queryset using 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)

Then generate a list of the items in the order you want:

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


来源:https://stackoverflow.com/questions/45693437/ordering-a-django-queryset-based-on-other-list-with-ids-and-scores

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!