user2453757 user2453757 - 3 months ago 6
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:

['John','Physics']
['Jim','Physics']
['Sam','Biology']
['Sarah','Biology']


And I want the template to output this:

Physics



John

Jim

Biology



Sam

Sarah

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.

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

My current veiws.py:

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


Here is my model.py

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>
<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">{{ mentor.name }}, {{ mentor.degree }}</h4>
<p class="text-center"><small>{{ mentor.department }}</small></p>
</div>
</div>
</div>
{% endfor%}
</div><!-- /.end row -->
{% endif %}

Answer

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 model.py