0

I want to use outerjoin operation on a subquery and also include values from the subquery also.

My code

q_responses = session.query(Candidate, CandidateProfile)
             .join(CandidateProfile, CandidateProfile.candidate_id == Candidate.id)

subq = (session.query(AppAction.candidate_id, Activity.archived)\
        .join(Activity, and_(AppAction.candidate_id == Activity.candidate_id, 
                             Activity.archived == 1)))\
        .subquery("subq")
responses = q_responses.outerjoin(subq, Candidate.id == subq.c.candidate_id).all()

So I get the result in this format

(Candidate, CandidateProfile)

But I also want to include the archived value from subquery in the result.

By reading many relevant posts from the internet, I have tried

  1. add_entity(subq.c.archived)
  2. with_entities
  3. add_column
  4. select_from

But all those have resulted in some error.

Please help me out.

1 Answer 1

3

Please share your error for when you try add_column. The code below should work just fine (assuming that it does work without like which contains add_column):

responses = (
    q_responses
    .add_column(subq.c.archived)  # @new
    .outerjoin(subq, Candidate.id == subq.c.candidate_id)
).all()

Also you could have created a query straight away with this column included:

subq = (
    session.query(AppAction.candidate_id, Activity.archived)
    .join(Activity, and_(AppAction.candidate_id == Activity.candidate_id,
                         Activity.archived == 1))
).subquery("subq")

q_responses = (
    session.query(Candidate, CandidateProfile, subq.c.archived)
    .join(CandidateProfile, CandidateProfile.candidate_id == Candidate.id)
    .outerjoin(subq, Candidate.id == subq.c.candidate_id)
).all()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I can now get those values from subquery to the outer query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.