在SQLAlchemy中加载已连接列的子集

时间:2016-03-13 05:45:59

标签: python sqlalchemy

我试图从SQLAlchemy中的多个连接表中加载一个列子集,并且无法找出神奇的语法。

这是我尝试做的一个简单例子。它会导致错误(如下):

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:无法找到名为' table2_val'的属性在此查询中映射的实体Mapper | Table1 | table1。

如何从这些多个表中挑选和选择列?

1 个答案:

答案 0 :(得分:1)