From a8cfb1d9d47d8e628d81c91c57627fe7bf7c34ce Mon Sep 17 00:00:00 2001 From: Jekel Date: Wed, 5 Sep 2018 17:40:57 +0300 Subject: [PATCH] Added SubqueryLoader to load model from query alias --- gino/loader.py | 7 +++++++ tests/test_loader.py | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/gino/loader.py b/gino/loader.py index 835d9178..e089c04a 100644 --- a/gino/loader.py +++ b/gino/loader.py @@ -160,6 +160,13 @@ def none_as_none(self, enabled=True): return self +class SubqueryLoader(ModelLoader): + def __init__(self, model, subquery, **extras): + super().__init__(model, **extras) + self.columns = [subquery.corresponding_column(column) for column + in model] + + class AliasLoader(ModelLoader): def __init__(self, alias, *columns, **extras): super().__init__(alias, *columns, **extras) diff --git a/tests/test_loader.py b/tests/test_loader.py index 2bdf9409..d2b766b1 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -151,6 +151,27 @@ def loader(row, context): assert u.team.parent.name == user.team.parent.name +async def test_adjanency_list_on_nested_load(user): + subquery = db.select(User).alias() + base_query = subquery.outerjoin(Team).select() + + query = base_query.execution_options(loader=(User.load('id'))) + u = await query.gino.first() + # Because here arrives team_id, not user_id, and replaces it + assert u.id is None + + from gino.loader import SubqueryLoader + query = base_query.execution_options(loader=SubqueryLoader(User, subquery, team=Team)) + u = await query.gino.first() + assert u.id == user.id + assert u.realname == user.realname + assert u.nickname == user.nickname + + assert isinstance(u.team, Team) + assert u.team.id == user.team.id + assert u.team.name == user.team.name + + async def test_adjacency_list_query_builder(user): group = Team.alias() u = await User.load(team=Team.load(parent=group.on(