Opened 10 years ago

Closed 10 years ago

#6821 closed (duplicate)

Aggregate support for QuerySets

Reported by: nicolaslara@… Owned by: Nicolas Lara
Component: Database layer (models, ORM) Version: queryset-refactor
Severity: Keywords: aggregation
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: UI/UX:


Add aggregate support for QuerySets according to what have been discussed in

The proposed syntax includes the two QuerySet modifiers _annotate_ and _aggregate_ to augment the objects with aggregate information and retrieve aggregate information regarding the whole QuerySet respectively.

The notation for defining the fields and aggregate functions to use would be done in filter-like syntax

Purchase.objects.all().aggregate(quantity__sum='total_adquisitions', payment__avg='mean_pay') 

with the possibility of specifying aggregates in object form for non aliased aggregates (only the simple form is intended, for a more complex approach to object aggregates: ). In this case a standard alias should be generated (i.e. quantity_sum, payment_avg)

Purchase.objects.all().aggregate(Sum('quantity'), Avg('payment'))

The GROUP BY is to be done internally. To specify the fields to be grouped it could be done with values()


No way to specify that only the aggregated fields should appear in the results is intended because this could be done with the modifiers proposed in #5420.

Ordering should be specified using order_by standard syntax with the aliased name.

==Extra ==

As extra things that could be implemented are:

  • Custom aggregate creation (possibly as follows)
    >>> my_own_aggregate = Aggregate( sum('field_1') * 'field2', 'default_name')
    >>> queryset.aggregate(purchases__price__custom=my_own_aggregate('alias')) 
  • F syntax for refering to other fields in the model.

Please refer to the discussion thread for a more in depth description

Attachments (1)

aggregate.diff (4.2 KB) - added by Nicolas Lara <nicolaslara@…> 10 years ago.
aggregate modifier 0.1

Download all attachments as: .zip

Change History (4)

Changed 10 years ago by Nicolas Lara <nicolaslara@…>

Attachment: aggregate.diff added

aggregate modifier 0.1

comment:1 Changed 10 years ago by Nicolas Lara <nicolaslara@…>

Has patch: set
Owner: changed from nobody to anonymous
Patch needs improvement: set
Status: newassigned

Added proof-of-concept patch that implements aggregate modifier. (No Joins/Aliases ...yet)

comment:2 Changed 10 years ago by Nicolas Lara <nicolaslara@…>

Owner: changed from anonymous to Nicolas Lara
Status: assignednew

comment:3 Changed 10 years ago by Russell Keith-Magee

Resolution: duplicate
Status: newclosed

Duplicate of #3566. You don't need to open a new ticket to work on aggregates - please continue discussions on the original ticket.

Note: See TracTickets for help on using tickets.
Back to Top