Using SQLAlchemy to check if column is in numeric ranges

20 views
Skip to first unread message

chat...@gmail.com

unread,
Aug 31, 2021, 5:07:48 AMAug 31
to sqlalchemy
Hello All!! , I have a list of age ranges i.e 18-25, 40-55 and more how can I make make a query using SQLAlchemy that will check if a Column is in ranges [18,25] OR [40-55] OR [60-70]
Regards,Christos

Simon King

unread,
Aug 31, 2021, 11:49:22 AMAug 31
to sqlal...@googlegroups.com
You want a combination of the "between" function/method:

https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.between

...and the "or_" function:

https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.or_

Something like this:

ranges = [(18, 25), (40, 55), (60, 70)]
conditions = [User.age.between(lower, upper) for (lower, upper) in ranges]
condition = sqlalchemy.or_(*conditions)
users = session.query(User).filter(condition).all()

Hope that helps,

Simon

On Tue, Aug 31, 2021 at 10:07 AM chat...@gmail.com <chat...@gmail.com> wrote:
>
> Hello All!! , I have a list of age ranges i.e 18-25, 40-55 and more how can I make make a query using SQLAlchemy that will check if a Column is in ranges [18,25] OR [40-55] OR [60-70]
> Regards,Christos
>
> --
> SQLAlchemy -
> The Python SQL Toolkit and Object Relational Mapper
>
> http://www.sqlalchemy.org/
>
> To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
> ---
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/e6a8019c-beb4-482a-9262-b752391a16f4n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages