Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return query with columns from multiple tables in SQLAlchemy

I haven't been able to find an answer to this, but I'm sure it must be somewhere. My question is similar to this question: sqlalchemy: how to join several tables by one query?

But I need a query result, not a tuple. I don't have access to the models, so I can't change it, and I can't modify the functions to use a tuple.

I have two tables, UserInformation and MemberInformation, both with a foreign key and relationship to Principal, but not to each other.

How can I get all the records and columns from both tables in one query? I've tried:

query = DBSession.query(MemberInformation).join(UserInformation, MemberInformation.pId == UserInformation.pId)

but it only returns the columns of MemberInformation

and:

query = DBSession.query(MemberInformation, UserInformation).join(UserInformation, MemberInformation.pId == UserInformation.pId)

but that returns a tuple.

What am I missing here?

like image 207
Niel Avatar asked Jan 29 '16 23:01

Niel


People also ask

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.

What is all () in SQLAlchemy?

method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.

What is subquery in SQLAlchemy?

The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

What does Flask-SQLAlchemy query return?

Flask-SQLAlchemy Query Returns the Database Class and the Data.


1 Answers

Only way I found to do this is to use statement instead of query:

stmt = select([table1, table2.col.label('table2_col')]).select_from(join(table1, table2, table1.t1_id == table2.t2_id))
obj = session.execute(stmt).fetchall()
like image 154
Sindhu Kothe Avatar answered Sep 23 '22 18:09

Sindhu Kothe