title: Simplifying Django Query Annotation
body: <p>I've 3 models and a function is called many times, but it generates 200-300 sql queries, and I'd like to reduce this number.</p>
  <p>I've the following layout:</p>
  <pre><code>class Info(models.Model):
      user = models.ForeignKey(User)
      ...
  
  class Forum(models.Model):
      info = models.ForeignKey(Info)
      datum = models.DateTimeField()
      ...
  
  class InfoViewed(models.Model):
      user = models.ForeignKey(User)
      infokom = models.ForeignKey(Info)
      last_seen = models.DateTimeField()
      ...
  </code></pre>
  <p>. I need to get all the number of new Forum messages, so only a number. At the moment it works so that I iterate over all the related Infokoms and I summerize all Forums having higher datum than the related InfoViewed's last_seen field.</p>
  <p>This works, however results ~200 queries for 100 Infos.</p>
  <p>Is there any possibility to fetch the same number within a few queries? I tried to play with annonate and django.db.models.Count, but I failed.</p>
  <p>Django: 1.11.16</p>
  <hr />
  <p>Currently I'm using this:</p>
  <pre><code>infos = Info.objects.filter(user_id=**x**)
  return sum(i.number_of_new_forums(self.user) \
              for i in infos)
  </code></pre>
  <p>and the number_of_new_forums looks like this:</p>
  <pre><code>info_viewed = self.info_viewed_set.filter(user=user)
  return len([f.id for f in self.get_forums().\
              filter(datum__gt = info_viewed[0].last_seen)])
  </code></pre>