title: Django bug when using distinct() and models.Sum()
body: <p>In Django, I have two models that are linked to each other, one having a ForeignKey to the other.</p>
  
  <p>The main model has an integer on it, and the other model (that links using a foreign key to the main model) has a boolean on it.</p>
  
  <pre><code>class Foo(models.Model):
      aaa = models.IntegerField()
  
  class Bar(models.Model):
      foo = models.ForeignKey(Foo)
      bbb = models.BooleanField()
  </code></pre>
  
  <p>What I want is to take all the Foo objects that have a bar.bbb set to True and add together all the <code>aaa</code>s. So I wrote the following:</p>
  
  <pre><code>query = Foo.objects.filter(
      bar__bbb=True
  )
  aaa_sum = query.aggregate(models.Sum("aaa"))['aaa__sum']
  </code></pre>
  
  <p>At first, the number I was getting was way too high to be true. After doing <code>query.count()</code> I realized that I was getting more objects than I should have recieved. I believed there could be a distinct issue because a <code>Foo</code> can have multiple <code>Bar</code>s. So I added <code>.distinct()</code> to the query as such:</p>
  
  <pre><code>query = Foo.objects.filter(
      bar__bbb=True
  ).distinct()
  aaa_sum = query.aggregate(models.Sum("aaa"))['aaa__sum']
  </code></pre>
  
  <p><code>.count()</code> after that point showed the number I was supposed to be getting, but the <code>aaa_sum</code> was still returning a huge number (at least 4 times what I get back if I just do <code>Foo.objects.all().aggregate(Sum("aaa"))</code>)</p>
  
  <p>After looking though django documentation, I found that <code>models.Count()</code> takes a <code>distinct=True</code> parameter that selects only distinct values
  ( <a href="https://docs.djangoproject.com/en/dev/topics/db/aggregation/#combining-multiple-aggregations" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/db/aggregation/#combining-multiple-aggregations</a> )
  So I even tried that:</p>
  
  <pre><code>query = Foo.objects.filter(
      bar__bbb=True
  ).distinct()
  aaa_sum = query.aggregate(models.Sum("aaa", distinct=True))['aaa__sum']
  </code></pre>
  
  <p>I believe this is a bug and there has to be some way to get around it or deal with it, but I've run out of ideas to try. Does anyone know how to deal with this problem? Am I going to have to loop through the query and add up each one individually?</p>