title: Django query with an aggregate function
body: <p>I have following models:</p>
  
  <pre><code>class TopicLabel(models.Model):
      name = models.CharField(max_length=256)
      order = models.IntegerField(null=True, blank=True)
      def __unicode__(self):
          return self.name
  
      def hasTopics():
          return TopicLabelConnection.objects.filter(labelId=self.id).count() &gt; 0
  
  class TopicLabelConnection(models.Model):
      topicId = models.ForeignKey(Topic, related_name='connection_topic')
      labelId = models.ForeignKey(TopicLabel, related_name='connection_label')
  
      def __unicode__(self):
          return self.labelId.name + ' / ' + self.topicId.title
  </code></pre>
  
  <p>In a certain view I want to create a list of all <code>TopicLabel</code>s, which have at least one connection (i. e. where <code>hasTopics</code> returns <code>true</code>).</p>
  
  <p>AFAIK it is impossible in Django to use instance methods in <code>filter</code> expressions (i. e. something like <code>TopicLabel.objects.filter(TopicLabel.hasTopics).order_by('order')</code> is impossible).</p>
  
  <p>What is the correct (Django-style) way to implement such query (preferably database-independent) ?</p>