To how list group by values and values in that category
<p>I want my template to display my group by category as a header, and then all the values for that group by category under it. For example, my table looks like this:</p>

<pre><code>['John','Physics']
['Jim','Physics']
['Sam','Biology']
['Sarah','Biology']
</code></pre>

<p>And I want the template to output this:</p>

<h1>Physics</h1>

<p>John</p>

<p>Jim</p>

<h1>Biology</h1>

<p>Sam</p>

<p>Sarah</p>

<p>I'm not sure what to put in my veiws.py as I would usually do this in SQL --> first group by category, then return all results in that category.</p>

<p>How would my veiws.py and template looks like to accomplish this? Thanks.</p>

<p>My current veiws.py:</p>

<pre><code>def department(request):
students = Students.objects.all().order_by('department')
return render(request, 'department.html', {
    'students':students,
})
</code></pre>

<p>Here is my model.py</p>

<pre><code>class Mentors(models.Model):
    name = models.CharField(max_length=100)
    degree = models.CharField(max_length=100)
    department = models.CharField(max_length=100)
</code></pre>

<p>And my template:</p>

<pre><code>{% if mentors %}
&lt;div class="row"&gt;
    {% for mentor in mentors %}
            &lt;div class="col-xs-12 col-sm-6 col-md-6 col-lg-4"&gt;
                &lt;h3&gt;{{ mentor.department }}&lt;/h3&gt;
            &lt;/div&gt;
            &lt;div class="col-xs-12 col-sm-6 col-md-6 col-lg-4"&gt;
                &lt;div class="thumbnail"&gt;
                    &lt;img src="{{ mentor.image.url }}" class="img-thumbnail"&gt;
                    &lt;div class="caption"&gt;
                        &lt;h4 class="text-center"&gt;{{ mentor.name }}, {{ mentor.degree }}&lt;/h4&gt;
                        &lt;p class="text-center"&gt;&lt;small&gt;{{ mentor.department }}&lt;/small&gt;&lt;/p&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
    {% endfor%}
&lt;/div&gt;&lt;!-- /.end row --&gt;
{% endif %}
</code></pre>

<p>The template (department.html) is the place where you're going to list all the student. You must have some similar to this:</p>

<pre><code>{% if students %}
    {% for student in students %}
        &lt;p&gt;{{ student.NAME_FIELD }}&lt;/p&gt;
        {{ student.DEPARTMENT_FIELD}}
    {% endfor %}
{% else %}
    No student are available.
{% endif %}
</code></pre>

<p>NAME_FIELD and DEPARTMENT_FIELD are the fields you declared in your model.py</p>

python django django-templates django-views django-1.10