Search code examples
pythonmysqlflaskponyorm

Python/ PonyORM /MySQL - Query using multiple URL Args


I have a URL https://example.com?p1=nai&p2=tex&p3=mak

I am using PONY ORM + Flask, on MYSQL. I would like to get all rows that match the URL parameters. The p1, p2 and p3 are fields on the table and can vary depending on user input

In MySQL I would have something like done [SELECT * FROM Table Name WHERE p1=nai&p2=tex]

Below my PONY/Flask code

query = select(r for r in Route)
for key,value in args.items():
    query = query.where("lambda r: r.%s == '%s'" %(key, value))
    print(r.id)

My query above just returns a match for the first parameter. i.e if p1 = nai then it will return all where p1= nai and ignore the rest. What am I missing? NB: Don't worry about SQL Injection


Solution

  • If you want to filter arguments with PonyORM by exact match, you can specify keyword arguments to filter or where methods:

    kwargs = {'name': 'John', 'age': 20}
    query = Route.select().where(**kwargs)
    

    for more complex queries it is possible to use getattr:

    for name, value in kwargs.items():
        query = query.where(lambda r: getattr(r, name) == value)
    

    My query above just returns a match for the first parameter.

    I suspect it is caused by some bug in your code, maybe you assign new query to query2 and then use previous query instead of query2.