简体   繁体   中英

Flask Sqlalchemy query using Joins and Filters

Hello there i am trying to query my database with three models,

Product, SalesDetails, And SalesReturns

I want to query on product model and return only products whose id s not in SalesDetails Or if the SalesDetails.Sale_id is in salesReturns.sale_id

Basically i want to return all products that are not sold or have been returned

I have tried something like this

P1= Product.query.outerjoin(salesDetails)
P2=p1.outerjoin(SalesReturns)
P3=p2.filter(or_(SalesDetails.product_id==None,SalesDetails.sale_id==SalesReturn.sale_id)).all

The problem is it returns all the products No matter if they are sold or not,

I tried testing it by selling same product twice and placing the saleid in salereturns

But the query returns all the products even if the second time the sale hasn't been returned.

I am really a beginner to database and sqlalchemy as well

It would be appreciated if you could help.

If you can't understand what i mean just ask me in the comment.

Thank you.

I don't understand well your data models but you can do something like this:

session.query(Product).outerjoin(SalesDetails, SalesDetails.product_id == None).\
outerjoin(SalesReturn, SalesReturn.sale_id == SalesDetails.sale_id).all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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