Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self join query to SQlAlchemy ORM using alias

I'm trying to convert the following SQL query to a SQlAlchemy statement and facing the error:

sqlalchemy.exc.InvalidRequestError: Don't know how to join to <AliasedInsp at 0x7fa9c5832be0; Task(Task)>. Please use the .select_from() method to establish an explicit left side, as well as providing an explicit ON clause if not present already to help resolve the ambiguity.

SQL Query:

select t2.* 
from task as t1 
inner join task as t2 on t1.g_id  = t2.g_id  
where t1.id = 'task_id';

SQlAlchemy statement:

table_a = aliased(Task)
table_b = aliased(Task)
query = (
    self.db.query(Task)
    .join(table_a, table_b).filter(table_b.group_id == table_a.group_id)
    .filter(table_a.id == task_id)
   )

Tried following the SQLAlchemy documentation on alias but could not figure out the error.

like image 782
Dee Avatar asked Apr 17 '26 15:04

Dee


1 Answers

t1 = aliased(Task)
t2 = aliased(Task)

query = (
    self.db.query(t2)
    .select_from(t1)
    .join(t2, t2.g_id == t1.g_id)
    .filter(t1.id == task_id)
   )
like image 59
van Avatar answered Apr 20 '26 09:04

van