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


i'm bit mentally stuck @ something, seems simple @ first glance.

i'm grabbing list of ids selected , scores sort them based on.

my current solution following:

ids = [1, 2, 3, 4, 5]  items = item.objects.filter(pk__in=ids) 

now need add score based ordering somehow i'll build 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'] score in scores]  items = item.objects.filter(pk__in=ids) 

so far - how add scores sort of aggregate , sort queryset based on them?

sort scores list, , fetch 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 descending order ids = [score['id'] score in scores] items = item.objects.in_bulk(ids) 

then generate list of items in order want:

items_in_order = [items[x] x in ids] 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

css - Language-specific LESS classes which contain @font-faces not working -