title: Django filter multiple foreign key relationships
body: <p>I want to list all of a teacher's students that have commented on each genre of blog posts. Below is my best effort, but I duplicate student names for each genre, so if they comment on multiple scary blog posts, their names are listed multiple times. How can I list each student name once next to each genre on the teacher profile page?</p>
  
  <p><strong>Models.py</strong> </p>
  
  <pre><code>class Genre(models.Model):
      name = models.CharField(max_length=200, unique=True)
  
  class Student(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile')
      username = models.CharField(max_length=128, unique=True)
      teacher = models.ForeignKey('Teacher', blank=True, null=True)
  
  class Teacher(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='teacher_profile')
      name = models.CharField(max_length=128, blank=True, unique=True)
  
  class BlogPost(models.Model):
      genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True)
  
  class Comment(models.Model):
      blogpost = models.ForeignKey(BlogPost, related_name='comments', on_delete = models.CASCADE, null=True)
      message = CharField(max_length=1000, blank=True)
      commenter = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE, null=True)
  </code></pre>
  
  <p><strong>Views.py</strong></p>
  
  <pre><code>def teacher_profile(request):
  student_list = Student.objects.filter(teacher__user=request.user)
  student_blogpost_list = BlogPost.objects.filter(comments__commenter__student_profile__teacher__user=request.user).distinct()
  student_genre_list = Genre.objects.filter(blogpost__in=student_blogpost_list).distinct()
  return render(
      request,
      'myapp/teacher_profile.html',
      context= {'student_list':student_list, 'student_blogpost_list':student_blogpost_list, 'student_genre_list':student_genre_list},
  )
  </code></pre>
  
  <p><strong>teacher_profile.html</strong></p>
  
  <pre><code>{% if student_genre_list %}
    &lt;h4&gt;Genres&lt;/h4&gt;
    {% for genre in student_genre_list %}
      Genre: {{ genre.name }} - Students: 
      {% for blogpost in genre.blogpost_set.all %}
        {% for comment in blogpost.comments.all %}
          {% if comment.commenter.student_profile in student_list %}
            {{ comment.commenter.student_profile.username }}
          {% endif %}
        {% endfor %}
      {% endfor %}
    &lt;br&gt;
    {% endfor %}
  {% endif %}
  </code></pre>