Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return all the columns with flask-sqlalchemy query join from two tables

I'm trying to do a join from two tables in flask-sqlalchemy and I want all the columns from both tables but if I execute:

Company.query.join(Buyer, Buyer.buyer_id == Company.id).all()

I have only the columns from Company (It returns, in fact, a Company object).

I know I can do something like:

Company.query.join(Buyer, Buyer.buyer_id == Company.id) \
             .add_columns(Buyer.id, Buyer.name, etc..).all()

It returns in this case:

(<Company 2>, 1, 'S67FG', etc..)

the problem is that I have a lot of columns and also I don't know how to marshmallow the returned obj with flask-marshmallow (with nested fields does not work).

Is there a way to return a new obj with columns from the two tables? What is for you the best way to manage these situations?

Any suggestion is highly appreciated. Thanks

like image 621
disgra Avatar asked Jan 11 '18 11:01

disgra


1 Answers

at the end I've achieved this by using this simple sqlalchemy query:

db.session.query(Company, Buyer).join(Buyer, Buyer.buyer_id == Company.id).all()

It returns:

(<Company 2>, <Buyer 1, 2>)
like image 129
disgra Avatar answered Nov 16 '22 01:11

disgra