Programming Tech Web Design

Django: Grouper – Show Additional Fields

In a system I’m developing that handles scheduling, I had a need to add some additional data to a report group header. I tried a few different approaches but nothing worked until I created a custom method on the model I was reporting on.

class MyModel(models.Model):
    job = models.CharField()
    address = models.CharField()
    start_date = models.DateTimeField()

    def custom_group_header(self):
        return self.job + "; " + self.address

This worked and got the needed data on the report, but seemed far too cumbersome to be the correct way.

I knew there had to be a better way.

Dennis Bottaro

The Better Way

A few days went by and I was asked to add more related data to the report group header. I almost created yet another custom method but just knew there had to be a better way. I googled around and came across a Django feature suggestion involving expanding a CHOICE field form the choice key to the choice value that was ultimately rejected. But the rejection comment held the answer I was looking for.

By virtue of the grouper having the list objects you can ask that list for the first object and access it’s model fields.

How to Refer to Additional Model Fields from the Grouper

group.list.0.field_to_display

So, for my next header change I did the following in the template without having to add unneeded code to the models.py file.

{% for job in jobs %}
	<tr>
		<td colspan="4"><strong>{{ job.grouper }}</strong></td>
		<td colspan="2" align="right"><strong>Start Date: {{ job.list.0.start_date|date:"Y-m-d" }}</strong></td>
	</tr>
	{% for task in job.list %}
	<tr>
		...
	</tr>
	{% endfor %}
{% endfor %}