Why is django group on wrong field? annotation ()

Why Django Group by id field? Here is the request:

MyModel.objects\
    .filter(
        status=1,
        created__gte=datestart,
        created__lte=dateend)\
    .values('terminal_id')\
    .annotate(
        total_pa=Sum('amount'),
        total_ar=Sum('amount_result')).query

      

But it orders and groups by the field pk.

... GROUP BY payment

. id

ORDER BY payment

. id

...

Instead

... GROUP BY payment

. terminal_id

ORDER BY payment

. terminal_id

...

+3


source to share


1 answer


See "Warning" here:

https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#interaction-with-default-ordering-or-order-by



Maybe the default order gets in the way. Try adding .order_by()

to the end of your query to make sure it clears order.

+4


source







All Articles