I'm trying to find a more pythonic way of executing SQL queries using the SQLalchemy ORM. Below is a sample SQL statement:
SELECT A.payment_plan_id, A.plan_id, A.amount, C.promo_code, B.sso_guid, B.user_id
FROM payment_plans as A
JOIN users as B ON A.user_id = B.user_id
JOIN invoices as C ON A.invoice_id = C.invoice_id
WHERE A.due_date::date < '01/01/2022'::date
AND (A.status = 'pending' OR A.status = 'failed')
Tried this approach:
orm_query = session.query(
select(
payment_plans.payment_plan_id,
payment_plans.plan_id,
payment_plans.amount,
invoices.promo_code,
users.sso_guid,
users.user_id,
)
.join(users, payment_plans.user_id == users.user_id)
.join(invoices, payment_plans.invoice_id == invoices.invoice_id)
.where(payment_plans.due_date < '01/01/2022')
.where(payment_plans.status in ["pending", "failed"])
)
and I'm always ending up with this error:
sqlalchemy.exc.ArgumentError: Column expression or FROM clause expected, got <sqlalchemy.sql.selectable.Select object at 0x7fe342d7ca60>. To create a FROM clause from a <class 'sqlalchemy.sql.selectable.Select'> object, use the .subquery() method.
I'm not sure what it means and I scoured google looking for answers. Any help is appreciated. Thanks!