Monday, August 15, 2011

Useful Queries and Tips in SQLAlchemy

Outer Join:
from opSQLAlchemy import Session
session = Session()
from Users import Users
from Sales import Sales
from sqlalchemy.orm import outerjoin
from sqlalchemy import or_
queries = session.query(Users, Sales).\
select_from(outerjoin(Users, Sales, Users.UserId == Sales.UserId)).\
filter(or_(Users.UserId == 3333, Sales.Flag == 1)).all()
Do hard-coded SQL query in SQLAlchemy
from opSQLAlchemy import engine
from sqlalchemy.sql import text
total = engine.execute(text("""
    SELECT sum(DonationAmount) as total
    FROM Donations
    WHERE OptionId = :option_id
    AND Paid = 1
    """), option_id=option_id)

No comments:

Post a Comment