Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

sqlmodel query with a subselect self join

$
0
0

Trying to do a self join on a model but am getting confused how to do so in sqlmodel ORM. Something equivalent to the use of following SQL in Postgresql.

SELECT tt.id, ttp.parent_name, tt.name  FROM target_table tt,        (select DISTINCT bb.parent_id, bbref.name parent_name          from target_table tt, target_table ttref         WHERE tt.parent_id is not null            AND tt.parent_id = ttref.id         order by 1) ttp WHERE tt.parent_id = ttp.parent_idORDER BY 1

I have a corresponding object built using sqlmodel ORM, like:

class TargetTable(SQLModel, table=True):...

Works fine for normal read / write.

with Session(engine) as session:    print(select(TargetTable))    for tt in session.exec(select(TargetTable)):        print(tt)

I now need to do an operation for which I need to retrieve some data as described in the SQL above. I am not sure - rather I do not know how to construct the definition and corresponding join with the second table.

I was trying along the lines of:

select(TargetTable).join(select(TargetTable.label('tt')).join(        (TargetTable.label('ttref').filter(tt.parent_id != NULL, tt.parent_id == ttref.id)        ).label(ttp)).filter(tt.parent_id = ttp.parent_id)

But it is not working and I am getting confused in exactly how to go about it.

Appreciate any pointers or a solution.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>