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
22๐
order_by
is for database stuff. Try to use sorted
instead:
sorted(MyModel.objects.all(), key=lambda m: m.calculate_rating)
- How does this Man-In-The-Middle attack work?
- In django, is there a way to directly annotate a query with a related object in single query?
- Calculate point based on distance and direction
- Where do I import the `DoesNotExist` exception in Django 1.10 from?
- Clean Up HTML in Python
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.
- Django's {{ csrf_token }} is outputting the token value only, without the hidden input markup
- Installing django 1.5(development version) in virtualenv
- Django prefetch_related's Prefetch, order_by?
- Django database delete specific number of entries