Skip to content

Commit

Permalink
Fix the aggregates using the wrong side of the join when doing a self…
Browse files Browse the repository at this point in the history
…-referential aggregate. (#333)
  • Loading branch information
grigi committed Mar 29, 2020
1 parent 71a91e6 commit 4963753
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Changelog
=========
0.15.22
-------
* Fix the aggregates using the wrong side of the join when doing a self-referential aggregation.

0.15.21
-------
* Fixed invalid ``var IN ()`` SQL generated using ``__in=`` and ``__not_in`` filters.
Expand Down
3 changes: 3 additions & 0 deletions tests/test_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,11 +213,14 @@ async def test_self_ref_filter_both(self):
async def test_self_ref_annotate(self):
self.maxDiff = None
root = await Employee.create(name="Root")
await Employee.create(name="Loose")
await Employee.create(name="1. First H1", manager=root)
await Employee.create(name="2. Second H1", manager=root)

root_ann = await Employee.get(name="Root").annotate(num_team_members=Count("team_members"))
self.assertEqual(root_ann.num_team_members, 2)
root_ann = await Employee.get(name="Loose").annotate(num_team_members=Count("team_members"))
self.assertEqual(root_ann.num_team_members, 0)

async def test_prefetch_related_fk(self):
tournament = await Tournament.create(name="New Tournament")
Expand Down
10 changes: 8 additions & 2 deletions tortoise/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pypika.terms import Function as BaseFunction

from tortoise.exceptions import ConfigurationError
from tortoise.fields.relational import ForeignKeyFieldInstance, RelationalField
from tortoise.fields.relational import BackwardFKRelation, ForeignKeyFieldInstance, RelationalField

if TYPE_CHECKING: # pragma: nocoverage
from tortoise.models import Model
Expand Down Expand Up @@ -54,9 +54,15 @@ def _resolve_field_for_model(
if field_split[0] in model._meta.fetch_fields:
related_field = cast(RelationalField, model._meta.fields_map[field_split[0]])
related_field_meta = related_field.model_class._meta
related_table = related_field_meta.basetable
if isinstance(related_field, BackwardFKRelation):
if table == related_table:
related_table = related_table.as_(
f"{table.get_table_name()}__{field_split[0]}"
)
join = (table, field_split[0], related_field)
function_joins.append(join)
field = related_field_meta.basetable[related_field_meta.db_pk_field]
field = related_table[related_field_meta.db_pk_field]
else:
field_object = model._meta.fields_map[field_split[0]]
if field_object.source_field:
Expand Down

0 comments on commit 4963753

Please sign in to comment.