| 293 | |
| 294 | |
| 295 | class Count(Aggregate): |
| 296 | function = "COUNT" |
| 297 | name = "Count" |
| 298 | output_field = IntegerField() |
| 299 | allow_distinct = True |
| 300 | empty_result_set_value = 0 |
| 301 | arity = 1 |
| 302 | allows_composite_expressions = True |
| 303 | |
| 304 | def __init__(self, expression, filter=None, **extra): |
| 305 | if expression == "*": |
| 306 | expression = Star() |
| 307 | if isinstance(expression, Star) and filter is not None: |
| 308 | raise ValueError("Star cannot be used with filter. Please specify a field.") |
| 309 | super().__init__(expression, filter=filter, **extra) |
| 310 | |
| 311 | def resolve_expression(self, *args, **kwargs): |
| 312 | result = super().resolve_expression(*args, **kwargs) |
| 313 | source_expressions = result.get_source_expressions() |
| 314 | |
| 315 | # In case of composite primary keys, count the first column. |
| 316 | if isinstance(expr := source_expressions[0], ColPairs): |
| 317 | if self.distinct: |
| 318 | raise ValueError( |
| 319 | "COUNT(DISTINCT) doesn't support composite primary keys" |
| 320 | ) |
| 321 | |
| 322 | source_expressions[0] = expr.get_cols()[0] |
| 323 | result.set_source_expressions(source_expressions) |
| 324 | |
| 325 | return result |
| 326 | |
| 327 | |
| 328 | class Max(Aggregate): |