Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why django group by wrong field? annotate()

Why Django Group by id Field? Here is queryset:

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 order and group by pk field.

... GROUP BY payment.id ORDER BY payment.id ...

Instead of

... GROUP BY payment.terminal_id ORDER BY payment.terminal_id ...

like image 824
ubombi Avatar asked Jun 25 '15 16:06

ubombi


1 Answers

See the "Warning" here:

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

Perhaps the default ordering is getting in the way. Try adding .order_by() to the end of your query to see if that clears the ordering.

like image 186
Tim Shaffer Avatar answered Sep 24 '22 01:09

Tim Shaffer