【问题标题】:Using the SQLAlchemy ORM to filter a query based on one object in a many-to-one relationship使用 SQLAlchemy ORM 根据多对一关系中的一个对象过滤查询
【发布时间】:2020-01-09 05:02:05
【问题描述】:

所以我有一张桌子carts,还有一张桌子cart_items。像这样(在伪代码中)将购物车连接到购物车项目。

购物车:cart_id = 1

cart_item:id = 12,cart_id = 1,in_stock = False

cart_item:id = 13,cart_id = 1,in_stock = False

cart_item:id = 14,cart_id = 1,in_stock = False

我想查询所有 carts 至少有一个 in_stock 值为 True 的 cart_item。

购物车:cart_id = 1

购物车:cart_id = 2

cart_item:id = 12,cart_id = 1,in_stock = False

cart_item:id = 13,cart_id = 1,in_stock = False

cart_item:id = 14,cart_id = 1,in_stock = False

cart_item:id = 15,cart_id = 2,in_stock = True

cart_item:id = 16,cart_id = 2,in_stock = False

cart_item:id = 17,cart_id = 2,in_stock = False

因此,给定此数据集,将返回一个 cart_id = 2 的购物车。

另外,我应该提一下,我知道我可以查询和检索所有对象,然后对该检测列表进行操作以过滤掉所有不符合此要求的对象,但我实际上需要以由于此 Web 应用程序中如何处理分页而导致的查询。

如果我可以在下面的模型中定义某种属性,那将是理想的。但我敢肯定这不会按现在的样子工作。

@property
def cart_has_in_stock(self):
    has_in_stock = False
    for item in self.cart.items:
      if item.in_stock:
        has_in_stock = True
    return has_in_stock

我刚刚想出了一个可以执行此操作的普通 SQL 查询,我现在只需要帮助将其移至 SQLAlchemy。我不太擅长 SQLAlchemy。

查询:select * from cart_items where cart_items.cart_id IN (select cart.id from cart_items as item INNER JOIN carts AS cart on item.cart_id = cart.id where item.stage = 'stock' group by cart.id) \G;

【问题讨论】:

    标签: python mysql sqlalchemy


    【解决方案1】:

    我想通了。

    sub_q = model.Session.query(model.Cart.id).\
            join(model.CartItem, model.Cart.id == model.CartItem.cart_id).\
            filter(
                model.CartItem.stage == 'stock'
            ).\
            group_by(model.Cart.id).\
            subquery()
    

    correct_q = model.Session.query(model.Cart).filter(model.Cart.id.in_(sub_q))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多