SQLAlchemy子查询,用于从另一个选项卡中计算值

2024-10-01 13:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

当需要返回值时(即不在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查询的一个示例:

^{pr2}$

我有一种感觉,这将是尴尬的简单,但我似乎不能破解代码,使这一工作。在

我已经试过了我能找到的几乎每一个样品,结果都是喜忧参半。如果省略.correlate()参数,则会收到以下错误:

'Alias' object has no attribute 'MasterProjectID'

我还尝试将以下语句添加到subquery()的末尾,但没有成功:

.correlate(ProjectMasters.MasterProjectID, ProjectInvoices.MasterProjectID)

如果我确实包含了correlate参数,则会收到以下错误:

TypeError: Boolean value of this clause is not defined

提前谢谢你的帮助。。。在


Tags: keytruedefaultbaseindexcolumnintegerclass
1条回答
网友
1楼 · 发布于 2024-10-01 13:24:39

通常我会使用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,
    )

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

^{pr2}$

相关问题 更多 >