Load subset of joined columns in SQLAlchemy

Viewed 4282

I'm trying to load a subset of columns from multiple joined tables in SQLAlchemy and can't figure out the magic syntax.

Here's a simple example of what I'm trying to do. It results in an error (below):

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, load_only

Base = declarative_base()

class Table1(Base):
    __tablename__ = 'table1'
    table1_id = Column(Integer, primary_key=True)
    table1_val = Column(String)
    r1 = relationship('Table2', backref = 'r2')


class Table2(Base):
    __tablename__ = 'table2'
    table2_id = Column(Integer, ForeignKey('table1.table1_id'), primary_key=True)
    table2_val = Column(String)


from sqlalchemy.orm import sessionmaker
some_engine = create_engine('postgresql://scott:tiger@localhost/')
Session = sessionmaker(bind=some_engine)
session = Session()
query = session.query(Table1).join(Table2).options(load_only('table1_val','table2_val'))

ArgumentError: Can't find property named 'table2_val' on the mapped entity Mapper|Table1|table1 in this Query.

How do I pick and choose columns from these multiple tables?

1 Answers
Related