martsberger / django-pivot

A module for pivoting Django Querysets
MIT License
210 stars 16 forks source link

Queryset and pivot table ordering #28

Closed martsberger closed 1 year ago

martsberger commented 1 year ago

From issue #5

I have noticed that you do not reorder the QuerySet before aggregation, which causes problems when aggregating on an annotated field, if it is already ordered by another field.

For example, consider the model:

class Blog(models.Model):
    date = models.DateField()
    category = models.CharField(max_length=50)
    content = models.TextField(default='')

    class Meta:
        order_by = ['date']

If I pivot on an annotated field like:

qs = Blog.objects.annotate(period=Trunc('date', 'year'))
pivot(qs, 'period', 'category', 'content', Count)

Aggregation does not work because the 'date' field must be part of the query's group by for the ordering to work.

Reordering fixes the problem, so this will work:

qs = Blog.objects.annotate(period=Trunc('date', 'year')).order_by('period')
pivot(qs, 'period', 'category', 'content', Count)

By default we will remove ordering from querysets passed to pivot, which is useful for any case where there is default ordering on the model. In the case that the client wants to specify an ordering for the resulting pivot table, we provide an optional ordering parameter to the pivot function.

martsberger commented 1 year ago

Fixed in this PR https://github.com/martsberger/django-pivot/pull/29