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_id
ORDER 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.
2
Answers
*** UPDATE: Adding the full non-working code in response to @python_user ask. I tried to follow the response advice from python_user to just include the query in the code here.
So, I changed the above to only include sqlalchemy for the aliasing and specifying the order_by indices from @python_users answer, and now it works for most part - except that for some reasons, it seems to be ignoring for the not null filter on the join.
The latest code is:
There is nothing SQLModel specific in this question, you have to use SQLAlchemy to do this. This approach emits the following query.
Here is a complete code that has the model defined in SQLAlchemy, but you should just be able to copy paste the query part and use with SQLModel.