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

Load model and custom columns in complex query result #308

jekel opened this Issue Aug 16, 2018 · 3 comments


None yet
2 participants
Copy link

jekel commented Aug 16, 2018

Is there some loader combination which can load Model and additional columns for each row?
For example, i need to make sql query with join and aggregation functions...[User, db.func.count()]).select_from(User.join(...))
and possibility to iterate over results like this
for user, users_count in await query...

  • GINO version: 0.7.5
  • Python version: 3.6.5
  • asyncpg version: 0.17.0
  • aiocontextvars version: 0.1.2
  • PostgreSQL version: 9.6.9

@fantix fantix added the question label Aug 16, 2018


This comment has been minimized.

Copy link

fantix commented Aug 16, 2018

This looks like a tuple loader with column loader. Please see example below:

import asyncio
import random
import string

import gino
from gino.loader import ColumnLoader

db = gino.Gino()

class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.Unicode())

class Visit(db.Model):
    __tablename__ = 'visits'

    id = db.Column(db.Integer(), primary_key=True)
    time = db.Column(db.DateTime(), server_default='now()')
    user_id = db.Column(db.ForeignKey(''))

async def main():
    async with db.with_bind('postgresql://localhost/gino'):
        await db.gino.create_all()

        for i in range(random.randint(5, 10)):
            u = await User.create(
                name=''.join(random.choices(string.ascii_letters, k=10)))
            for v in range(random.randint(10, 20)):
                await Visit.create(

        visits = db.func.count(
        q =[
        ).gino.load((User, ColumnLoader(visits)))
        async with db.transaction():
            async for user, visits in q.iterate():
                print(, visits)

        await db.gino.drop_all()

This comment has been minimized.

Copy link

jekel commented Aug 16, 2018

Cool, that works!
Can you update documentation please with such example? (i didn't find anything like this there..)


This comment has been minimized.

Copy link

fantix commented Aug 16, 2018

Yeah sounds like a good idea, will do!

@fantix fantix closed this in 5c192a3 Oct 25, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment