Search code examples
python-3.xflasksqlalchemy

Sqlalchemy query with_entities for multiple table name


Below is my code.

sometable1.query.with_entities(
    sometable2.user,
    sometable3.user_name,
    seomtable4.user
).join(
    sometable2,
    sometable2.user_id == sometable1.user_id
).join(
    sometable3,
    sometable3.user_id==sometable2.user_id
).join(
    sometable4,
    sometable4.user_id==sometable3.user_id
).filter(
    sometable1.user_id==2
).all()

The above query gives the following error.

sqlalchemy.exc.InvalidRequestError: Can't determine which FROM clause to join from, 
there are multiple 
FROMS which can join to this entity. Please use the .select_from()

But when i add sometable1.user in the query then its working fine.

sometable1.query.with_entities(
    sometable1.user,   #<-------------- added sometable1.user
    sometable2.user,
    sometable3.user_name,
    seomtable4.user
).join(
    sometable2,
    sometable2.user_id == sometable1.user_id
).join(
    sometable3,
    sometable3.user_id==sometable2.user_id
).join(
    sometable4,
    sometable4.user_id==sometable3.user_id
).filter(
    sometable1.user_id==2
).all()

I don't want sometable1.user, is there any way to remove it ? The output gives sometable1.user along with other data in a list. But i dont want sometable1.user in the output.


Solution

  • This worked for me.

    sometable1.query.with_entities(
        sometable2.user,
        sometable3.user_name,
        seomtable4.user
    ).select_from(   #<-------------- select_from
      sometable1
    ).join(
        sometable2,
        sometable2.user_id == sometable1.user_id
    ).join(
        sometable3,
        sometable3.user_id==sometable2.user_id
    ).join(
        sometable4,
        sometable4.user_id==sometable3.user_id
    ).filter(
        sometable1.user_id==2
    ).all()
    

    Have to use select_from then include sometable1.