gpt-4-0314· openai
Suzhen/CodeChat
sqlchemy filter but int also not like search
- User
sqlchemy filter but int also not like search
- Assistant
In SQLAlchemy, if you want to filter an integer column using the not like operation, you can use the
not_function along with thecastfunction. Here's an example:First, let's assume you have a table called
my_tablewith an integer column namedid:from sqlalchemy import create_engine, Column, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class MyTable(Base): __tablename__ = 'my_table' id = Column(Integer, primary_key=True) # other columns... engine = create_engine('sqlite:///example.db') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session()Now, to filter
MyTablerows based on theidcolumn using the "not like" search:from sqlalchemy import not_, cast, String search_string = "1%" # This is an example search string query = session.query(MyTable).filter(not_(cast(MyTable.id, String).like(search_string))) result = query.all()In this example, the
castfunction is used to convert the integeridcolumn to a string, then thelikefunction is used to perform the like search. Finally, thenot_function is used to invert the result.