How to sort by computed value in django

Hi, I want to sort objects based on computed value in django ... how to do this?

Here is an example of a stack overflow model of a user profile that explains my predicament:

class Profile(models.Model): user = models.ForeignKey(User) def get_reputation(): ... return reputation reputation = property(get_reputation) 

So, let's say I want to sort users by reputation. How should I do it? I know that you cannot just do this:

 Profile.objects.order_by("-reputation") 

Thanks for all your help :)

+5
python sorting django web-applications django-models
May 30 '09 at 11:34
source share
3 answers

If you need to sort in the database (because you have many records and need to paginate them, for example), the only real option is to turn the reputation into a denormalized field (for example, updated in the overridden save() method on the model).

+3
May 31 '09 at 1:41 a.m.
source share

Since your calculation code only exists inside Python, you also need to do the sorting in Python:

 sorted (Profile.objects.all (), key = lambda p: p.reputation) 
+16
May 30 '09 at 23:54
source share

As of Django-1.8, you can sort a QuerySet using a query expression expression , if the calculated value can be displayed in SQL, you can also use annotations for the model as an order_by term.

 from django.db.models import F Profile.objects.annotate(reputation=(F('<field>') + ...)).order_by("-reputation") 

Basic operations such as + , - , * , / and ** can be used with F() . In addition, there are several other functions such as Count , Avg , Max , ...

References:

See also SO Q & A: QuerySet Order by Aggregation Field Value

+5
Nov 04 '15 at 7:44
source share



All Articles