Adrian Serna Adrian Serna - 2 months ago 5x
Python Question

Can I do a dynamic comparison on SQLAlchemy?

I have this model:

class PUC(Base):
pucId = Column(Integer, primary_key=True)
asset = Column(TINYINT)
article = Column(TINYINT)
more values ...
more values ...

And I need to do a query dynamically (This way I tried):

pucs = session.query(PUC).filter(PUC[unique_by_param] == 1).all()

The value of
come from the Frontend.
An example of

What I really need is a way to do.
session.query(PUC).filter(PUC.asset == 1)
session.query(PUC).filter(PUC.article == 1)
dynamically, like the first way I tried.

The result using (
) is
TypeError: 'DeclarativeMeta' object is not subscriptable

There is a way I have used before, but isn't pretty way to do that, but isn't pretty way to do that:

# this is a accounting table, so this have around 250 columns
#and this special columns be around 70 variables...
#So this isn't an option o do this.
if unique_by_param == 'asset':
q = (PUC.asset == 1)
elif unique_by_param == 'article':
q = (PUC.article)
elif ...more values:

pucs = session.query(PUC).filter(or_(*q))


Here's an approach that uses filter_by and keyword argument unpacking:

keyword = {unique_by_param : 1}