[Python] Can I find out if an instance of a SQL Alchemy Model meets the filter requirements...

Discussão em 'Python' iniciado por Stack, Setembro 4, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have the SQLAlchemy code shown below. It retrieves all the users who are older than 28 years old.

    Now suppose I create a new User u2 = User(name='Bart', age=66).

    I want to find out if u2 matches the filter of my_query without going back to the DB and scanning the entire table. Can I do it?

    from sqlalchemy import create_engine, Column, Integer, String
    from sqlalchemy.orm import sessionmaker, declarative_base

    Base = declarative_base()

    class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

    engine = create_engine('sqlite:///:memory:')
    Base.metadata.create_all(engine)

    Session = sessionmaker(bind=engine)
    session = Session()

    # Add some data
    session.add_all([
    User(name='Alice', age=30),
    User(name='Bob', age=25),
    User(name='Charlie', age=35)
    ])
    session.commit()

    # Filter users older than 28
    my_query = session.query(User).filter(User.age > 28)
    users = my_query.all()
    for user in users:
    print(f"Name: {user.name}, Age: {user.age}")

    Continue reading...

Compartilhe esta Página