title: Django: order a queryset by the sum of annotated fields?
body: <p>I'm building a Django site for discussions.  Users can participate in discussions and can also cast votes of approval for discussions and messages in the discussions.  A simplified data model is as follows:</p>
  
  <pre><code>class Discussion:
      name = models.CharField(max_length=255)
  
  class Message:
      owner = models.ForeignKey(User, related_name='messages')
      body = models.TextField()
      discussion = models.ForeignKey(Discussion, related_name='messages')
  
  class MessageApprovalVote:
      owner = models.ForeignKey(User, related_name='message_approval_votes')
      message = models.ForeignKey(Message, related_name='approval_votes')
  
  class DiscussionApprovalVote:
      owner = models.ForeignKey(User, related_name='discussion_approval_votes')
      discussion = models.ForeignKey(Discussion, related_name='approval_votes')
  </code></pre>
  
  <p>I want to select the top 20 "most active" discussions, which means ordering by the sum of the number of messages, total number of message approval votes, and number of discussion approval votes for that discussion, or (in pseudocode):</p>
  
  <pre><code># Doesn't work
  Discussion.objects.
      order_by(Count('messages') + 
               Count('approval_votes') + 
               Count('messages__approval_votes'))
  </code></pre>
  
  <p>Using annotations, I can calculate the totals of each of the three scoring factors:</p>
  
  <pre><code>scores = Discussion.objects.annotate(
      total_messages=Count('messages', distinct=True),
      total_discussion_approval_votes=Count('approval_votes', distinct=True),
      total_message_approval_votes=Count('messages__approval_votes', distinct=True))
  </code></pre>
  
  <p>I then thought I was on to something when I found the <code>extra</code> method:</p>
  
  <pre><code>total_scores = scores.extra(
      select={
          'score_total': 'total_messages + total_discussion_approval_votes + total_message_approval_votes'
      }
  )
  </code></pre>
  
  <p>and would then be able to do:</p>
  
  <pre><code>final_answer = total_scores.order_by('-score_total')[:20]
  </code></pre>
  
  <p>but the <code>extra</code> call gives a <code>DatabaseError</code>:</p>
  
  <pre><code>DatabaseError: column "total_messages" does not exist
  LINE 1: SELECT (total_votes + total_messages + total_persuasions) AS...
  </code></pre>
  
  <p>and thus I was foiled.  Can the <code>extra</code> method not reference <code>annotate</code>d fields?  Is there another way to do what I'm trying to do, short of using a raw sql query?  I'm using Postgres if that makes a difference.</p>
  
  <p>Any insights would be greatly appreciated!</p>