title: django get list of distinct 'children' of ForeignKey related model (and do this in template?)
body: <p>I'm making a database of released music albums</p>
  
  <p>models.py</p>
  
  <pre><code>class Image(models.Model):
      image = models.ImageField(....
  
  class Album(models.Model):
      title = models.CharField(....
  
  class Release(models.Model):
      album = models.ForeignKey(Album)
      cover_art = models.ForeignKey(Image, blank=True, null=True, on_delete=models.SET_NULL)
  </code></pre>
  
  <p>In my template (at the moment I'm using generic views) I have:</p>
  
  <pre><code>{% for a in album_list %}
      {% for r in a.release_set.all %}
          {% if r.cover_art %}
          # display cover art image
          {% endif %}
      {% endfor %}
  {% endfor %}
  </code></pre>
  
  <p>The problem is that sometimes an album has been released several times with identical cover art, in which case I'd like to display the image only once, with some text listing the releases it pertains to.</p>
  
  <p>I've tried:</p>
  
  <pre><code>{% for i in a.release_set.cover_art %}
  {% for i in a.release_set.cover_art_set %}
  {% for i in a.release_set.all.cover_art %}
  {% for i in a.release_set.all.cover_art_set %}
  </code></pre>
  
  <p>Or in a simpler case, I'd at least like to display the images smaller if there are more than one of them.</p>
  
  <pre><code>{% if a.release_set.count &gt; 1 %} # works but displays duplicate images
  {% if a.release_set.cover_art_set.count &gt; 1 %} # doesn't work (see above)
  </code></pre>
  
  <p>Is it possible to get a list of objects related by reversing this ForeignKey lookup then asking for the set of their children? The only way I can think of is by assembling some tuples/lists in the view.</p>