1

i have 2 models Car and Rating. People rate cars (duhh). I have wrote a simple get_average_score() method which gets the average score of the Car, below are my models.

class Car(models.Model):
  def get_average_score(self):
    return self.rating_set.aggregate(Avg('score'))

class Rating(models.Model):
  car = models.ForeignKey(Car)
  score = models.IntegerField(blank=False, null=False)

Basically what i want is "Top Cars", where I'm ordering get_average_score() desc.

How would i do this?

dotty
  • 40,405
  • 66
  • 150
  • 195

1 Answers1

1

No but you could do this using annotate e.g.

Car.objects.annotate(score=Avg('rating__score').order_by('-score')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
JamesO
  • 25,178
  • 4
  • 40
  • 42
  • That would be Avg, i thought you could render that method as a property, so i could do order_by('-get_average_score') – dotty Jul 18 '11 at 14:43
  • Yep sorry avg, as far as i thought you could not order by custom method. – JamesO Jul 18 '11 at 14:46
  • This is what I'm looking for, but as you said you cannot order by custom methods http://stackoverflow.com/questions/981375/using-a-django-custom-model-method-property-in-order-by – dotty Jul 18 '11 at 14:49