title: How to group by AND aggregate with Django
body: <p>I have a fairly simple query I'd like to make via the ORM, but can't figure that out..</p>
  
  <p>I have three models:</p>
  
  <p>Location (a place), Attribute (an attribute a place might have), and Rating (a M2M 'through' model that also contains a score field)</p>
  
  <p>I want to pick some important attributes and be able to rank my locations by those attributes - i.e. higher total score over all selected attributes = better.</p>
  
  <p>I can use the following SQL to get what I want:</p>
  
  <pre><code>select location_id, sum(score) 
      from locations_rating 
      where attribute_id in (1,2,3) 
      group by location_id order by sum desc;
  </code></pre>
  
  <p>which returns</p>
  
  <pre><code> location_id | sum 
  -------------+-----
            21 |  12
             3 |  11
  </code></pre>
  
  <p>The closest I can get with the ORM is:</p>
  
  <pre><code>Rating.objects.filter(
      attribute__in=attributes).annotate(
      acount=Count('location')).aggregate(Sum('score'))
  </code></pre>
  
  <p>Which returns </p>
  
  <pre><code>{'score__sum': 23}
  </code></pre>
  
  <p>i.e. the sum of all, not grouped by location.</p>
  
  <p>Any way around this? I could execute the SQL manually, but would rather go via the ORM to keep things consistent.</p>
  
  <p>Thanks</p>