Django Regroup Template Tag

Learn via video courses
Topics Covered

Overview

Django regroup template tag is used for grouping of the objects list by a particular attribute and then in our template we can iterate over that group.

Definition and Usage

Objects from the existing list are grouped by the Django regroup tag and we can further iterate over those grouped objects.

Let us take an example of a list of students and every student has a class and name attribute. Now we want these students will be grouped by their class and then we can display grouped students in our template.

Now in our template student_list.html, we will Django regroup template tag for grouping students by class.

In this example, {% regroup %} is used to group the students by the class attribute and assign the result to class_list. Then, we iterate over class_list, and for every group, we use {{ class.grouper }} for displaying the class name and using another loop for listing the students in that class. So we will get the following output

Students by Class

I

  • Steve
  • Shiang
  • Jhanvi

II

  • Mrinal
  • Risha

Syntax

The syntax of the Django regroup tag is given below:

Parameters

Parameter nameDescription
objectRequired. An object or list on which you want to perform regrouping.
object.propertyRequired. Specify the property name that you want to group by.
newnameRequired. A new name you want to give to the returned object as per your requirements.

Conclusion

  • Django regroup template tag is used for grouping the objects list by a particular attribute and then in our template, we can iterate over that group.
  • {% regroup object by object.property as newname %} is a syntax of django regroup template.