title: Django ORM - filter by count of related across multiple levels
body: <p>I have following three models (simplified):</p>
  
  <pre class="lang-py prettyprint-override"><code>from django.db import models
  
  class UserProfile(models.Model):
      pass
  
  class Gallery(models.Model):
      user_profile = models.ForeignKey('UserProfile')
  
  class Photo(models.Model):
      gallery = models.ForeignKey('Gallery')
  </code></pre>
  
  <p>On profile detail I want to show <strong>all galleries that have at least one photo</strong>.</p>
  
  <p>I tried to go this way:</p>
  
  <pre class="lang-py prettyprint-override"><code>Gallery.objects.all().filter(user_profile__pk=x). \
      annotate(count_photos=Count('photo_set')).filter(count_photos__gt=0)
  </code></pre>
  
  <p>But this leads to an error:</p>
  
  <p><code>FieldError: Cannot resolve keyword 'photo_set' into field. Choices are: id, user_profile</code></p>
  
  <p>I understand, that <code>Gallery.objects.all()</code> is <code>Queryset</code>, so this is probably not possible. Solution could be to start from <code>Photo</code>:</p>
  
  <pre class="lang-py prettyprint-override"><code>Photo.objects.all().filter(gallery__user_profile__pk=x)
  </code></pre>
  
  <p>But I need to iterate in template over galleries and not over photos.</p>