[Fixed]-Django order_by a property

10๐Ÿ‘

โœ…

There is no way to do this. One thing you can do is to create a separate database field for that model and save the calculated rating in it. You can probably override the save method of the model and do the calculations there, after that you can only refer to the value.

You can also sort the returned QuerySet using Python sorted. Take into account that the sorting approach using the built-in sorted function increases a lot the computational complexity and itโ€™s not a good idea to use such code in production.

For more information you can check this answer: https://stackoverflow.com/a/981802/1869597

๐Ÿ‘คJordan Jambazov

22๐Ÿ‘

order_by is for database stuff. Try to use sorted instead:

sorted(MyModel.objects.all(),  key=lambda m: m.calculate_rating)
๐Ÿ‘คAlexandre

3๐Ÿ‘

The best way to achieve what you want, is by using the Case and When statements. This allows you to keep the final result in QuerySet instead of list ๐Ÿ˜‰

ratings_tuples = [(r.id, r.calc_rating) for r in MyModel.objects.all()]  
ratings_list = sorted(ratings_tuples, key = lambda x: x[1])  # Sort by second tuple elem

So here is our sorted list ratings_list that holds IDs and ratings of the elements in a sorted way

pk_list = [idx for idx, rating in ratings_list]  
from django.db.models import Case, When
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)])  
queryset = MyModel.objects.filter(pk__in=pk_list).order_by(preserved)  

Now, using Case and When statements, we are able to do the queryset sorting itself by the IDs from the list we already have. (Django Docs for details).
Had a similar situation and needed a solution. So found some details on this post https://stackoverflow.com/a/37648265/4271452, it works.

๐Ÿ‘คIulian Pinzaru

Leave a comment