数据库
首页 > 数据库> > python – 用于从另一个表中求值的SQLAlchemy子查询

python – 用于从另一个表中求值的SQLAlchemy子查询

作者:互联网

当需要返回值(即未在WHERE中使用)时,我正在努力理解在SQLAlchemy中执行子查询的正确语法.

我正在使用声明式方法.

有两种模型使用:

class ProjectInvoices(Base):
    InvoiceID = Column(Integer(unsigned=True), default=0, primary_key=True, autoincrement=True)
    MasterProjectID = Column(Integer(unsigned=True), index=True, nullable=False)
    ExpenseAmount = Column(Numeric(10, 2), default=0)
    HoursAmount = Column(Numeric(10, 2), default=0)
    IsVoid = Column(Boolean, default=0, index=True)
    IsSubmit = Column(Boolean, default=0, index=True)

class ProjectMasters(Base):
    MasterProjectID = Column(Integer(unsigned=True), default=0, primary_key=True, autoincrement=True)
    MasterProjectName = Column(Unicode(255))
    MasterProjectMemo = Column(UnicodeText)
    IsActive = Column(Boolean, default=0, index=True)

查询的要点是通过使用子查询对相关发票求和来确定每个项目的当前发票金额.还有其他原因在子查询中完成,而不仅仅是一个连接,所以我真的需要弄清楚子查询问题.

这是我当前SA查询的一个示例:

sqry = session.query(
  func.sum(
    func.ifnull(ProjectInvoices.ExpenseAmount, 0) 
    + func.ifnull(ProjectInvoices.HoursAmount, 0))).label('billed_total')
).filter(and_(ProjectInvoices.IsVoid == 0, ProjectInvoices.IsSubmit == 1)
).subquery()

result = session.query(
  ProjectMasters.MasterProjectID, 
  ProjectMasters.MasterProjectName, 
  sqry.columns.billed_total.label('invoice_total')
).filter(ProjectMasters.IsActive == 1).all()

我有一种感觉,这将是简单的尴尬,但我似乎无法破解代码让这个工作.

我已经尝试了几乎所有可以找到混合结果的样本.如果我省略.correlate()参数,我收到以下错误:

'Alias' object has no attribute 'MasterProjectID'

我也尝试将以下语句添加到子查询()的末尾而没有任何运气:

.correlate(ProjectMasters.MasterProjectID, ProjectInvoices.MasterProjectID)

如果我确实包含correlate参数,那么我收到以下错误:

TypeError: Boolean value of this clause is not defined

我在这里先向您的帮助表示感谢…

解决方法:

通常我会使用column_property来处理这样的要求,例如

class ProjectMasters(Base):
    ...

    billed_total = column_property(
        select(
            [func.sum(
                func.coalesce(ProjectInvoices.ExpenseAmount, 0)
                + func.coalesce(ProjectInvoices.HoursAmount, 0)
            )],
            and_(
                MasterProjectID == ProjectInvoices.MasterProjectID,
                ProjectInvoices.IsVoid == False,
                ProjectInvoices.IsSubmit == True,
            ),
        ).label('billed_total'),
        deferred=True,
    )

之后,您可以像普通属性一样使用它,例如

result = session.query(
    ProjectMasters.MasterProjectID, 
    ProjectMasters.MasterProjectName, 
    ProjectMasters.billed_total.label('invoice_total'),
).filter(ProjectMasters.IsActive == 1).all()

标签:declarative,python,subquery,sqlalchemy
来源: https://codeday.me/bug/20190902/1793888.html