Will Hua
Will Hua

Reputation: 1748

SQLAlchemy 0.9.4 filtering for a group

I am using SQLAlchemy 0.9.4 with Python 3.4.1 and MySQL on a CentOS Server. I am trying to filter by seeing if a certain value in a column is any of multiple values. For example, if x in [1, 2, 3, 4, 5] I would like the value to be selected. How could I go about doing that?

Upvotes: 0

Views: 60

Answers (1)

van
van

Reputation: 77012

Use in_ operator in the filter expression. Working code below, but please go through SQLAlchemy documentation.

from sqlalchemy import create_engine, Table, Column, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///:memory:', echo=True)
session = sessionmaker(bind=engine)()
Base = declarative_base(engine)

class MyTable(Base):
    __tablename__ = 'my_table'
    id =  Column(Integer, primary_key=True)
    x  = Column(Integer)
Base.metadata.create_all(engine)

# this is the query
qry = session.query(MyTable).filter(MyTable.x.in_([1,2,3,4,5]))
result = qry.all()

Upvotes: 1

Related Questions