views:

67

answers:

1

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.

+5  A: 

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])
Daniel Roseman
+1 For simplistic and great use of lambda :)
Bartek