Skip to content

Instantly share code, notes, and snippets.

@albarrentine
Created June 19, 2011 03:31
Show Gist options
  • Save albarrentine/1033728 to your computer and use it in GitHub Desktop.
Save albarrentine/1033728 to your computer and use it in GitHub Desktop.
SQLAlchemy's tuple_ construct
"""
Assuming a model and table "Thingy" with columns type and id (I love generic association tables,
so you will see this a lot in schemas I write).
While this seems like a headache for multigets, there is a very easy way to do an IN operation on such a table using SQL tuples (index obviously needs to be on both columns for it to be fast):
SELECT * FROM thingy WHERE (type, id) IN (('foo', 1), ('bar', 2));
And SQLAlchemy has a great construct for just this case...
"""
from sqlalchemy.sql.expression import tuple_
Session.query(Thingy).filter(tuple_(Thingy.type, Thingy.id).in_([('foo', 1), ('bar', 2)])).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment