user2453757 user2453757 - 1 month ago 4x
Python Question

To how list group by values and values in that category

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:


And I want the template to output this:







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

How would my and template looks like to accomplish this? Thanks.

My current

def department(request):
students = Students.objects.all().order_by('department')
return render(request, 'department.html', {

Here is my

class Mentors(models.Model):
name = models.CharField(max_length=100)
degree = models.CharField(max_length=100)
department = models.CharField(max_length=100)

And my template:

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


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

{% if students %}
    {% for student in students %}
        <p>{{ student.NAME_FIELD }}</p>
        {{ student.DEPARTMENT_FIELD}}
    {% endfor %}
{% else %}
    No student are available.
{% endif %}

NAME_FIELD and DEPARTMENT_FIELD are the fields you declared in your