Skip to content

Add support for ArrayAgg aggregations #183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions django_mock_queries/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,14 @@
AGGREGATES_MAX = 'MAX'
AGGREGATES_MIN = 'MIN'
AGGREGATES_AVG = 'AVG'
AGGREGATES_ARRAY = 'ARRAY_AGG'
AGGREGATES = (
AGGREGATES_SUM,
AGGREGATES_COUNT,
AGGREGATES_MAX,
AGGREGATES_MIN,
AGGREGATES_AVG,
AGGREGATES_ARRAY,
)

DjangoQ = locate('django.db.models.Q')
Expand Down
3 changes: 2 additions & 1 deletion django_mock_queries/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ def aggregate(self, *args, **kwargs):
AGGREGATES_COUNT: lambda: len(values),
AGGREGATES_MAX: lambda: max(values),
AGGREGATES_MIN: lambda: min(values),
AGGREGATES_AVG: lambda: sum(values) / len(values)
AGGREGATES_AVG: lambda: sum(values) / len(values),
AGGREGATES_ARRAY: lambda: values,
}[expr.function]()

if len(values) == 0 and expr.function == AGGREGATES_COUNT:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,19 @@ def test_query_aggregate_performs_avg_on_queryset_field(self):
[x.foo for x in items if x.foo is not None]
)

def test_query_aggregate_performs_array_on_queryset_field(self):
items = [
MockModel(foo=5),
MockModel(foo=10),
MockModel(foo=15),
]
self.mock_set.add(*items)

expr = MagicMock(function=AGGREGATES_ARRAY, source_expressions=[MockModel(name='foo')])
result = self.mock_set.aggregate(expr)

assert result['foo__array_agg'] == [x.foo for x in items]

def test_query_aggregate_with_none_only_field_values_performs_correct_aggregation(self):
items = [
MockModel(foo=None),
Expand Down