SpectralAngel
SpectralAngel

Reputation: 48

Django adds extra columns to group by

I have the following queryset:

Pago.objects.filter(created__range=(self.inicio, self.fin)).values('tipo__nombre').annotate(monto=Sum('monto'))

And it is producing the following SQL:

SELECT "invoice_tipopago"."nombre", SUM("invoice_pago"."monto") AS "monto" FROM "invoice_pago" INNER JOIN "invoice_tipopago" ON ( "invoice_pago"."tipo_id" = "invoice_tipopago"."id" ) WHERE "invoice_pago"."created" BETWEEN 2015-01-01 00:00:00-06:00 AND 2015-06-04 14:18:00-06:00 GROUP BY "invoice_tipopago"."nombre", "invoice_pago"."modified", "invoice_pago"."created" ORDER BY "invoice_pago"."modified" DESC, "invoice_pago"."created" DESC

It is adding the extra modified and created columns that I am not specifying, and i would like to know how to avoid it. It should be noticed that Pago is a derived from the django-extensions TimeStampedModel class.

Thanks in advance.

Upvotes: 1

Views: 226

Answers (1)

Renan Ivo
Renan Ivo

Reputation: 1388

I took a look at TimeStampedModeland it set a default ordering in the class meta:

class TimeStampedModel(models.Model):
""" TimeStampedModel
An abstract base class model that provides self-managed "created" and
"modified" fields.
"""
created = CreationDateTimeField(_('created'))
modified = ModificationDateTimeField(_('modified'))

class Meta:
    get_latest_by = 'modified'
    ordering = ('-modified', '-created',)
             # ^^^^^^^^^^^^^^^^^^^^^^^^^^
    abstract = True

see in github

You could overwrite that providing another filter to order by (like tipo__nombre or monto), ex:

Pago.objects.filter(
    created__range=(self.inicio, self.fin)
).values(
    'tipo__nombre'
).annotate(
    monto=Sum('monto')
).order_by(
    'tipo__nombre'
)

Upvotes: 2

Related Questions