File tree Expand file tree Collapse file tree 3 files changed +38
-1
lines changed
clickhouse_backend/models Expand file tree Collapse file tree 3 files changed +38
-1
lines changed Original file line number Diff line number Diff line change 1
1
### 1.5.0
2
+ - feat: add ` argMax ` aggregation https://clickhouse.com/docs/sql-reference/aggregate-functions/reference/argmax
2
3
- feat: #133 : Fix simultaneous queries error when iteration is interrupted
3
4
- feat: #130 : Add ` distributed_migrations ` database setting to support distributed migration queries.
4
5
- feat: #129 : Add ` toYearWeek ` datetime functionality
Original file line number Diff line number Diff line change 1
- from django .db .models import aggregates
1
+ from django .db .models import aggregates , fields
2
2
from django .db .models .expressions import Star
3
3
4
4
from clickhouse_backend .models .fields import UInt64Field
@@ -67,3 +67,24 @@ class uniqTheta(uniq):
67
67
68
68
class anyLast (Aggregate ):
69
69
pass
70
+
71
+
72
+ class ArgMax (Aggregate ):
73
+ function = "argMax"
74
+ name = "ArgMax"
75
+ arity = 2
76
+
77
+ def __init__ (self , value_expr , order_by_expr , ** extra ):
78
+ if "output_field" not in extra :
79
+ # Infer output_field from value_expr
80
+ if hasattr (value_expr , "output_field" ):
81
+ extra ["output_field" ] = value_expr .output_field
82
+ else :
83
+ # Fallback: assume CharField
84
+ extra ["output_field" ] = fields .CharField ()
85
+ expressions = [value_expr , order_by_expr ]
86
+ super ().__init__ (* expressions , ** extra )
87
+
88
+ def as_sql (self , compiler , connection , ** extra_context ):
89
+ self .extra ["template" ] = "%(function)s(%(expressions)s)"
90
+ return super ().as_sql (compiler , connection , ** extra_context )
Original file line number Diff line number Diff line change 10
10
uniqHLL12 ,
11
11
uniqTheta ,
12
12
)
13
+ from clickhouse_backend .models .aggregates import ArgMax
13
14
14
15
from .models import WatchSeries
15
16
@@ -170,6 +171,20 @@ def setUpTestData(cls):
170
171
# Use bulk_create to insert the list of objects in a single query
171
172
WatchSeries .objects .bulk_create (watch_series_list )
172
173
174
+ def test_argMax (self ):
175
+ result = (
176
+ WatchSeries .objects .values ("show" )
177
+ .annotate (episode = ArgMax ("episode" , "date_id" ))
178
+ .order_by ("show" )
179
+ )
180
+
181
+ expected_result = [
182
+ {"show" : "Bridgerton" , "episode" : "S1E1" },
183
+ {"show" : "Game of Thrones" , "episode" : "S1E1" },
184
+ ]
185
+
186
+ self .assertQuerysetEqual (result , expected_result , transform = dict )
187
+
173
188
def _test_uniq (self , cls_uniq ):
174
189
result = (
175
190
WatchSeries .objects .values ("show" , "episode" )
You can’t perform that action at this time.
0 commit comments