1

I have a model:

class Person(models.Model):
    score1 = models.FloatField(default=0)
    score2 = models.FloatField(default=0)
    score3 = models.FloatField(default=0)

and I need to sort the records by the average score (i.e. (score1 + score2 + score3)/3) in descending order.

For the following list of Persons:

p1 = Person(score1=3, score2=4, score3=5) # avg = 4
p2 = Person(score1=3, score2=2, score3=1) # avg = 2

the result should be:

[<p2>, <p1>]
3
  • You can sort the fields manually after querying, or add a field to your model called average that you update on def clean(self)
    – Jessie
    Mar 13, 2017 at 19:58
  • it is very hard to understand what you want to do. can you try to better explain your problem?
    – user3850
    Mar 13, 2017 at 20:26
  • i made some changes hope it's more clear now Mar 13, 2017 at 20:35

1 Answer 1

4

You can use F-expressions to annotate each row with the average score:

from django.db.models import F

ps_with_avg = Person.objects.annotate(
    avg=(F('score1')+F('score2')+F('score3'))/3
)

and then order them by the avg score like so:

ordered_ps = ps_with_avg.order_by('-avg')

Check the generated SQL to verify it does what you want:

print(ordered_ps.query)
7
  • 1
    That's a great improvement for me! Posted the same answer with you sir. Glad I could make it.
    – nik_m
    Mar 13, 2017 at 20:39
  • yeah this works great.thanks a lot.really appreciate it. Mar 13, 2017 at 20:43
  • Don't I deserve an upvote :). At least to reach zero!
    – nik_m
    Mar 13, 2017 at 20:44
  • I did give an upvote, but mine won't be shown since my reputations is less than 15 :) Mar 13, 2017 at 21:10
  • hello @Bahman Rouhani in the solution of hop he forgot to make the end result descending as you ask so you need to pus the - in the annotated field order_by(-avg) like this: ordered_ps = ps_with_avg.order_by('-avg')
    – Reidel
    Mar 14, 2017 at 18:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.