Skip to content

Commit

Permalink
Fix bug join with aggregation (#328)
Browse files Browse the repository at this point in the history
  • Loading branch information
hqsz authored Mar 22, 2020
1 parent 21e7281 commit cd82404
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Changelog
* Default ``values()`` & ``values_list()`` now includes annotations.
* Annotations over joins now work correctly with ``values()`` & ``values_list()``
* Ensure ``GROUP BY`` precedes ``HAVING`` to ensure that filtering by aggregates work correctly.
* Fix bug with join query with aggregation

0.16.1
------
Expand Down
16 changes: 16 additions & 0 deletions tests/test_aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,22 @@ async def test_aggregation(self):
with self.assertRaisesRegex(ConfigurationError, "name__id not resolvable"):
await Event.all().annotate(tournament_test_id=Sum("name__id")).first()

async def test_nested_aggregation_in_annotation(self):
tournament = await Tournament.create(name="0")
await Tournament.create(name="1")
event = await Event.create(name="2", tournament=tournament)

team_first = await Team.create(name="First")
team_second = await Team.create(name="Second")

await event.participants.add(team_second)
await event.participants.add(team_first)

tournaments = await Tournament.annotate(
events_participants_count=Count("events__participants")
).filter(id=tournament.id)
self.assertEqual(tournaments[0].events_participants_count, 2)

async def test_aggregation_with_distinct(self):
tournament = await Tournament.create(name="New Tournament")
await Event.create(name="Event 1", tournament=tournament)
Expand Down
1 change: 0 additions & 1 deletion tortoise/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ def resolve(self, model: "Type[Model]", table: Table) -> dict:

if isinstance(self.field, str):
function = self._resolve_field_for_model(model, table, self.field, *self.default_values)
function["joins"] = reversed(function["joins"])
return function
else:
field, field_object = F.resolver_arithmetic_expression(model, self.field)
Expand Down

0 comments on commit cd82404

Please sign in to comment.