Dynamic SQL / SQLALCHEMY query to variable parameters

Question:

I´ve been working on a database of millions of credit cards transactions. When filtering such data, the main parameter is the company name (name of the company where did you user your card).

As strings are not easy to filter, I have something like : Searching for Amazon and getting Amazonia (rain florest…).

So, I want to create a query where I can input the name I want. e.g., this is the current query (does not have the "not like" option)

select_stmt = select(
        text(f"'{company}' as company"),
        func.upper(table.c.name_cia),
        table.c.date,
        table.c.value)
        .where(func.upper(table.c.name_cia).contains(str(cia_name).upper()))

Now I need to upgrade this query to insert a ‘not like’ parameter (or sqlalchemy equivalent), but as the exclusion name can be variable, sometimes I have zero, sometimes I have 4 different names do exclude.

How can I dynamically setup my query depending of the lenght of a list?

Asked By: FábioRB

||

Answers:

As @Gord Thompson noticed, its the same situation as this
Thanks man!

In my case I just made just the coding below (a loop to include the new where condition for each item a in a list).

for item in termos_exclusão:
   select_stmt = select_stmt.where(credit_card.c.name_company.not_like(str(wrong_name)))
Answered By: FábioRB
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.