First, let's take a look at the example model I'm working with.
class Shipment(models.Model):
description = models.TextField()
created = models.DateTimeField(auto_now_add=True);
I wanted to display these Shipments grouped by they day they had been created and I wanted that day formated like "2008-12-22". Since the 'created' field of the Shipment model is a datetime.datetime instance which, when viewed as a string, looks like "2008-12-23 19:16:06.700114". That was a bit too verbose and besides, I wanted shipments grouped by day, not by microsecond!
My solution was to a add a property (of course!) to my model and see if I could use that in the regroup tag. Here's what that looked like:
class Shipment(models.Model):
description = models.TextField()
created = models.DateTimeField(auto_now_add=True);
def _get_ship_date(self):
return self.created.date()
ship_date = property(_get_ship_date)
Then in my regroup tag, I could do this:
<ul>
{% regroup shipments by ship_date as shipments_by_date %}
{% for ship_date in shipments_by_date %}
<li>Shipments for {{ ship_date.grouper }} </li>
<ol>
{% for shipment in ship_date.list %}
<li> {{ shipment.description }} </li>
{% endfor %}
</ol>
{% endfor %}
</ul>
Hey, that worked, but this was another of my newbie missteps because there was an aspect to the regroup tag that I had overlooked (this series should be called RTFM maybe?). You can apply a filter to the attribute you are regrouping on like so:
{% regroup ship_list by created|date:"Y-n-d" as shipments_by_date %}
And you're done.