Django通过

时间:2015-06-05 16:52:54

标签: python django

我有以下查询集:

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

它正在生成以下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

它正在添加我未指定的额外修改和创建的列,我想知道如何避免它。应该注意的是,Pago是从django-extensions TimeStampedModel类派生而来的。

提前致谢。

1 个答案:

答案 0 :(得分:2)

我查看了TimeStampedModel并在课程ordering中设置了默认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

你可以覆盖那个提供另一个过滤器来排序(例如tipo__nombremonto),例如:

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