Created
January 6, 2017 16:26
-
-
Save maxdanilov/42f2e175616f918d0e2a150ddda531e7 to your computer and use it in GitHub Desktop.
Operators applied to static values and not columns in SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Imagine Model has start_time field and you want to filter all events that | |
# fall into an intersection of two DateTimeRanges (tsrange in PostreSQL). | |
# Doing daterange intersections in Python is tedious, Postgresql is much better at it. | |
# That requires applying operators to a value (not a column) and that is not so | |
# straightforward: | |
query = DB.session.query(Model) | |
range1 = DateTimeRange(datetime(2017, 1, 5, 0), datetime(2017, 1, 5, 10, 5)) | |
range2 = DateTimeRange(datetime(2017, 1, 5, 10, 0), datetime(2017, 1, 5, 15, 0)) | |
# intersection is DateTimeRange(datetime(2017, 1, 5, 10, 0), datetime(2017, 1, 5, 10, 5)) | |
query = query.filter(Model.start_time.op('<@')(sqlalchemy.sql.expression.bindparam("r1", range1).op('*')(range2))) | |
# <@ is 'contained in' operator | |
# * is an intersection operator | |
return query.all() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment