'Display items grouped in month together using django regroup
I have a model with following fields
examname | month
a1 Jan
a2 Jan
a3 Jan
b1 Feb
b2 March
b3 March
I want to display exams in each month grouped in months
example
Jan : a1 a2 a3
Feb : b1
March: b2 b3
I am using the following queryset
def getallexams(request):
exams = exam.objects.annotate(month_total=Count('month')).order_by('month')
print(exams)
context={
"exams" : exams,
}
return render(request, 'exams/index.html',context)
Below is the code I am using to render the template:
{% regroup exams by month as month_list %}
<div class="accordion" >
{% for month in month_list %}
{{month.grouper }}
# I am not sure how to loop through this month to display each exam
{% endfor %}
Solution 1:[1]
The official documentation has a pretty nice description of how to use regroup tag https://docs.djangoproject.com/en/4.0/ref/templates/builtins/
{% regroup exams by month as month_list %}
<div class="accordion" >
{% for month in month_list %}
{{month.grouper }}
{% for exam in month.list %}
{{ exam.examname }}
{% endfor %}
{% endfor %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rootart |
