Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

sqlchemy filter but int also not like search

  1. User

    sqlchemy filter but int also not like search

  2. Assistant

    In SQLAlchemy, if you want to filter an integer column using the not like operation, you can use the not_ function along with the cast function. Here's an example:

    First, let's assume you have a table called my_table with an integer column named id:

    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 MyTable rows based on the id column 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 cast function is used to convert the integer id column to a string, then the like function is used to perform the like search. Finally, the not_ function is used to invert the result.