带内部联接的SELECT语句的Flask SQLAlchemy语法

时间:2018-11-18 18:24:10

标签: python sqlalchemy

我对Flask和SQLalchemy还是很陌生,并且努力将SELECT语句转换为Query。我将不胜感激。

这是声明:

select * from product_store inner join my_store on product_store.storeid = my_store.storeid where product_store.productid = 1 and my_store.userid = 2 order by product_store.price, my_store.priority;

这是我最初的尝试:

productstore = ProductStore.query.join(MyStore, ProductStore.storeid==MyStore.storeid).filter_by(ProductStore.productid==3, MyStore.userid ==2).order_by(ProductStore.price).first()

我收到“ TypeError:filter_by()接受1个位置参数,但给出了3个”

2 个答案:

答案 0 :(得分:0)

在Ilja的帮助下,我更正了该查询。

        productstore = ProductStore.query.join(MyStore, ProductStore.storeid==MyStore.storeid).filter(ProductStore.productid==3).filter(MyStore.userid ==2).order_by(ProductStore.price).first()

答案 1 :(得分:0)

  • filter_by()与关键字参数表达式一起使用。
  

关键字表达式是从查询的主要实体或作为调用Query.join()的目标的最后一个实体中提取的。

所以您需要写为:

productstore = ProductStore.query.filter_by(productid=3) \
                                 .join(MyStore, ProductStore.storeid==MyStore.storeid) \
                                 .filter_by(userid=2) \
                                 .order_by(ProductStore.price).first()
  • filter()与SQL表达式一起使用,可以将字段比较的结果作为参数。

在SQL表达式中,您可以编写:

productstore = ProductStore.query.join(MyStore, ProductStore.storeid==MyStore.storeid) \
                           .filter(ProductStore.productid==3, 
                                   MyStore.userid ==2) \
                           .order_by(ProductStore.price).first()