繁体   English   中英

SQLAlchemy 相关表列值的总和

[英]SQLAlchemy Aggregate sum of related table column values

我有桌子:

class Cart(Base):
    items = relationship('Item', backref='cart')

class Item(Base):
    price = sa.Column(sa.Integer, default=0)
    cart_id = sa.Column(
        sa.Integer,
        sa.ForeignKey(
            'Cart.id',
            ondelete='CASCADE',
        )
    )

我想按此聚合总和聚合购物车项目价格和订单购物车列表的总和,如何在 SA 中构建查询? 谢谢!

您可以将其实现为混合属性(您必须设置关系lazy='dynamic'

from sqlalchemy import func, select

class Cart(Base):
    items = relationship("Item", backref="cart", lazy="dynamic")

    @hybrid_property
    def items_price(self):
        return self.items.with_entities(func.sum(Item.price)).scalar()

    @items_price.expression
    def items_price(cls):
        return (
            select(func.sum(Item.price))
            .where(Item.cart_id == cls.id)
            .label("items_price")
        )


class Item(Base):
    price = Column(Integer, default=0)
    cart_id = Column(
        Integer,
        ForeignKey(
            "Cart.id",
            ondelete="CASCADE",
        ),
    )

您现在可以在查询中使用items_price

carts = session.query(Cart).order_by(Cart.items_price.desc())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM