简体   繁体   中英

How to sort model by values in a dictionary?

In Django, I have a model, and I will have a dictionary having the id's of objects in this model as keys, and a weight as values. I would like to use these weights in an order_by:

MyModel.objects.filter(title__icontains=query).order_by( 'value_from_the_dictionary' )

How to make this work?

I can't put the weights in the model, as they will be different in each call of this view, and I don't want to save them anywhere, they will be calculated on each query of the URL.

Sorting in order_by is done by the database, so if those elements aren't in the database you can't order by them. You will have to get the queryset and then do the ordering in Python.

qs = MyModel.objects.filter(title__icontains=query)
qs.sort(key=lambda x: mydict[x])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM