title: Django 2 distinct model field items
body: <p>I am trying to get a list of distinct items in a field of a module and then display all the items associated with that field.</p>
  
  <p>For example, in a school administration system there is a school module and a student model. Each student has a color associated with them as a 'color' field. I want to create a page where the page lists all the distinct colors in the school and then under each color a list of students that belong to that color.</p>
  
  <p>Would I write this function in views?</p>
  
  <p>Here is what I have so far in views.py:</p>
  
  <pre><code>class SchoolColorDetailView(DetailView):
      model=models.School
      template_name='school_app/school_color_detail.html'
  
      def get_context_data(self,**kwargs):
          context = super().get_context_data(**kwargs)
          context['colors']=Student.objects.all().order_by('color').distinct('color')
  </code></pre>
  
  <p>This will get me a list of all colors (but not by school). Is there any way to only get the colors by school and then all the students associated with that color? Do I have to create a dictionary for this?</p>
  
  <p>Any help would be appreciated.</p>
  
  <p>Thanks!</p>
  
  <p>Update:</p>
  
  <p>Here are the models:</p>
  
  <pre><code>class School(models.Model):
      name = models.CharField(max_length=256)
      principal = models.CharField(max_length=256)
      location = models.CharField(max_length=256)
  
  
      def __str__(self):
          return self.name
  
      def get_absolute_url(self):
      return reverse("school_app:school_detail",kwargs={'pk':self.pk})
  
  
  class Student(models.Model):
      name = models.CharField(max_length=256)
      color = models.CharField(max_length=256)
      school = models.ForeignKey(School,related_name='students', on_delete="Protect")
  
      def __str__(self):
          return self.name
  
      def get_absolute_url(self):
          return reverse("school_app:student_detail",kwargs={'pk':self.pk})
  </code></pre>
  
  <p>Second update:</p>
  
  <p>I am trying to make a template that looks something like this (not sure the best way to do that):</p>
  
  <pre><code>{% for color in colors %}
   &lt;ul&gt;
     &lt;li&gt;{{color}}
       {% for student in color %}
       &lt;ul&gt;
         &lt;li&gt;{{student}}&lt;/li&gt;
       &lt;/ul&gt;
       {% endfor %}
     &lt;/li&gt;
   &lt;/ul&gt;
  {% endfor %}
  </code></pre>