|
0
|
1 |
""" |
|
|
2 |
Classes to represent the definitions of aggregate functions. |
|
|
3 |
""" |
|
|
4 |
|
|
|
5 |
class Aggregate(object): |
|
|
6 |
""" |
|
|
7 |
Default Aggregate definition. |
|
|
8 |
""" |
|
|
9 |
def __init__(self, lookup, **extra): |
|
|
10 |
"""Instantiate a new aggregate. |
|
|
11 |
|
|
|
12 |
* lookup is the field on which the aggregate operates. |
|
|
13 |
* extra is a dictionary of additional data to provide for the |
|
|
14 |
aggregate definition |
|
|
15 |
|
|
|
16 |
Also utilizes the class variables: |
|
|
17 |
* name, the identifier for this aggregate function. |
|
|
18 |
""" |
|
|
19 |
self.lookup = lookup |
|
|
20 |
self.extra = extra |
|
|
21 |
|
|
|
22 |
def _default_alias(self): |
|
|
23 |
return '%s__%s' % (self.lookup, self.name.lower()) |
|
|
24 |
default_alias = property(_default_alias) |
|
|
25 |
|
|
|
26 |
def add_to_query(self, query, alias, col, source, is_summary): |
|
|
27 |
"""Add the aggregate to the nominated query. |
|
|
28 |
|
|
|
29 |
This method is used to convert the generic Aggregate definition into a |
|
|
30 |
backend-specific definition. |
|
|
31 |
|
|
|
32 |
* query is the backend-specific query instance to which the aggregate |
|
|
33 |
is to be added. |
|
|
34 |
* col is a column reference describing the subject field |
|
|
35 |
of the aggregate. It can be an alias, or a tuple describing |
|
|
36 |
a table and column name. |
|
|
37 |
* source is the underlying field or aggregate definition for |
|
|
38 |
the column reference. If the aggregate is not an ordinal or |
|
|
39 |
computed type, this reference is used to determine the coerced |
|
|
40 |
output type of the aggregate. |
|
|
41 |
* is_summary is a boolean that is set True if the aggregate is a |
|
|
42 |
summary value rather than an annotation. |
|
|
43 |
""" |
|
|
44 |
klass = getattr(query.aggregates_module, self.name) |
|
|
45 |
aggregate = klass(col, source=source, is_summary=is_summary, **self.extra) |
|
|
46 |
# Validate that the backend has a fully supported, correct |
|
|
47 |
# implementation of this aggregate |
|
|
48 |
query.connection.ops.check_aggregate_support(aggregate) |
|
|
49 |
query.aggregates[alias] = aggregate |
|
|
50 |
|
|
|
51 |
class Avg(Aggregate): |
|
|
52 |
name = 'Avg' |
|
|
53 |
|
|
|
54 |
class Count(Aggregate): |
|
|
55 |
name = 'Count' |
|
|
56 |
|
|
|
57 |
class Max(Aggregate): |
|
|
58 |
name = 'Max' |
|
|
59 |
|
|
|
60 |
class Min(Aggregate): |
|
|
61 |
name = 'Min' |
|
|
62 |
|
|
|
63 |
class StdDev(Aggregate): |
|
|
64 |
name = 'StdDev' |
|
|
65 |
|
|
|
66 |
class Sum(Aggregate): |
|
|
67 |
name = 'Sum' |
|
|
68 |
|
|
|
69 |
class Variance(Aggregate): |
|
|
70 |
name = 'Variance' |