用于求和另一个表中的值的 SQLAlchemy 子查询

发布于 2024-12-10 09:42:20 字数 1865 浏览 0 评论 0原文

当需要返回值时(即不在 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'

我还尝试将以下语句添加到 subquery() 的末尾,但没有任何运气:

.correlate(ProjectMasters.MasterProjectID, ProjectInvoices.MasterProjectID)

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

TypeError: Boolean value of this clause is not defined

感谢您提前的帮助...

I am struggling to understand the proper syntax for executing a subquery in SQLAlchemy when the value needs to be returned (i.e. not used in the WHERE).

I am using the declarative approach.

There are two models being used:

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)

The point of the query is to determine the current amount invoiced for each project by using a subquery to sum the related invoices. There are other reasons this is being done in a subquery rather than just a join so I really need to figure out the subquery issue.

This is an example of my current SA query:

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()

I have a feeling this is going to be embarrassing simple but I can't seem to crack the code on getting this to work.

I have tried just about every sample I can find with mixed results. If I leave out the .correlate() argument I receive the following error:

'Alias' object has no attribute 'MasterProjectID'

I have also tried adding the following statement to the end of the subquery() without any luck:

.correlate(ProjectMasters.MasterProjectID, ProjectInvoices.MasterProjectID)

If I do include the correlate argument then I receive the following error:

TypeError: Boolean value of this clause is not defined

Thanks for the help in advance...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三寸金莲 2024-12-17 09:42:20

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

Usually I would use a column_property to handle such requirement, e.g.

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,
    )

After that, you can use it like an ordinary attribute, e.g.

result = session.query(
    ProjectMasters.MasterProjectID, 
    ProjectMasters.MasterProjectName, 
    ProjectMasters.billed_total.label('invoice_total'),
).filter(ProjectMasters.IsActive == 1).all()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文