Why isn't there a simple group_by in Django?
<p>I have a model:</p>

<pre><code>class Person(models.MyModel):
    department = models.ForeignKey('Department')
    start_date = models.DateField()

class Department(models.SomeModel):
    name = models.CharField()
</code></pre>

<p>I want, in my template, to be able to create a simple table where I can group people by two attributes: <code>department__name</code> and <code>start_date</code>.</p>

<p>In this way, people with the same department name which started in the same date would be displayed in the same row.</p>

<p>I know there is a template tag called <code>regroup</code>, but I can only give three arguments, and only one of them can be the <code>grouper</code>.</p>

<p>Well, I thought I could do this query in my <code>view.py</code> with something like this: </p>

<pre><code>Person.objects.all().group_by('start_date','department__name')
</code></pre>

<p>But I was wrong. There is no such method.</p>

<p>Any way to achieve this in a simple way?</p>

<h3>Edit 1</h3>

<p>By the same attribute I mean the classe's objects. For example:</p>

<p>Let's suppose this is the database:</p>

<p>Name | Department | Start date</p>

<p>Bob | Sales | 12-12-2012</p>

<p>Sara | Sales | 12-12-2012</p>

<p>John | Finance | 13-11-2012</p>

<p>Then the of the following function would be something like this:</p>

<p>function: </p>

<pre><code>Person.objects.all().group_by('department__name', 'start_date')
</code></pre>

<p>output: </p>

<p>Sales | 12-12-2012 | Bob, Sara</p>

<p>Finance | 13-11-2012 | John</p>

<p>This way, Sara and John have been grouped by department <strong>AND</strong> start date.</p>

<p>The way you can do your group_by in django is using <code>values</code> and <code>aggregate</code>.</p>

<p>For example, you can achieve the result you want by making it like this:</p>

<pre><code>Person.objects.all().values('department__name', 'start_date').annotate(Count('start_date'))
</code></pre>

<p>However I believe you can not get all the names in a single string, and AFAIK you also could not do it in a simple <code>GROUP BY</code> on mysql, for example.</p>

<p>EDIT: just now I've understood that you want to group_by two values, so you would do something like:</p>

<pre><code>    Person.objects.all().values('department__name', 'start_date')\
        .annotate(Count('start_date'))\
        .annotate(Count('department__name'))\
        .values_list('department__name','start_date')
</code></pre>

python django