JavaSa
JavaSa

Reputation: 6242

Querying with joins in sql alchemy and avoiding select all

I would like to know wether there is a way to combine joining two tables, and retrieving the two entities only with their relevant columns.

I want to avoid doing a thing such select * after joining two tables and getting only column id from Table A and column address from table B. Working with python2.7 I heard of sqlalchemy feature called with_entities, but not sure how can it be mixed with this kind of join, lets work on this example from sqlalchemy tutorial:

u, a  = session.query(User, Address).\
                     filter(User.id==Address.user_id).\
                     filter(Address.email_address=='[email protected]').\
                     first():

Upvotes: 9

Views: 19564

Answers (1)

jackotonye
jackotonye

Reputation: 3853

Check out Query.join()

id, address  = session.query(A.id, B.address).\
             join(B, B.user_id == A.id).\ 
             filter(A.email_address=='[email protected]').\
             first()

This can be done using a join or outerjoin depending on the use case, joins can be implicit or explicit. The .join second argument is the explicit join statement.

Upvotes: 9

Related Questions