title: Django - ordering a filter by the sum of ForeignKey values?
body: <p>I have the following model:</p>
  
  <pre><code>class User:
      name = models.CharField( max_length = 200 )
      problem_user = models.BooleanField(default=False)
      def points_total(self):
          points_added = PointsAdded.objects.filter(user=self)
          points_total = 0
          for point in points_added:
              points_total += point.points
          return points_total
  
  class PointsAdded:
      points = models.IntegerField()
      user = models.ForeignKey( User )
  </code></pre>
  
  <p>I want to return a list of Users for whom problem_user is False, ordered by the points_total field. </p>
  
  <p>I know that I need to use annotate (as <a href="https://stackoverflow.com/questions/476017/django-queryset-order-by-method">described here</a>) but I am a newbie and don't really know how to use it, because the example is slightly different from my case. This doesn't work:</p>
  
  <pre><code>leaders = VideoUser.objects.filter(problem_user=False).pointsadded_set. \
                  .annotate(points_total=Sum('points__value')) \
                  .order_by('points_total')
  </code></pre>
  
  <p>The alternative seems to be to write out the whole of my points_total function inside the annotate() section of the expression above - is that possible?</p>
  
  <p>Is there a way to achieve what I want to do with Django functionality or must I fall back to SQL? Or should I redesign my database :)</p>