Adrian Serna Adrian Serna - 3 months ago 14
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
unique_by_param
come from the Frontend.
An example of
unique_by_param
is:
{str}'asset'
,
{str}'article'
,
{str}'another_model_value'


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

The result using (
PUC[unique_by_param]
) 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))

Answer

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

keyword = {unique_by_param : 1}
session.query.filter_by(**keyword).all()
Comments