Search code examples
pythonrestgetweb2pyweb2py-modules

How do I use web2py smart_query for a GET request?


So I'm trying to use smart_query in web2py to find specific values in a db, but the only explanation I can find is in the web2py book and it's not very clear. The example GET request from the book is formatted like this:

def GET(search):
    try:
        rows = db.smart_query([db.person, db.pet], search).select()
        return dict(result=rows)
    except:
        ...

I'm confused as to what values I would put in place of db.person and db.pet. Here is what the book says on it:

The method db.smart_query takes two arguments:
    a list of field or table that should be allowed in the query
    a string containing the query expressed in natural language

I'm thinking the first value would be the database I'm searching, but then I don't know what the second value would be. The book makes it sound like it should be the string I'm searching for, but I think that that's what the variable search is for.

Could someone please help me understand what exactly each argument is supposed to do?


Solution

  • The first argument to smart_query is a list of DAL Table and/or Field objects (a Table object in the list will simply be expanded to include all of the table's fields). This list determines which fields can be included in the query.

    The second argument is the query itself, which can include field names and comparison operators (and their natural language counterparts) as well as "and" and "or" to expression conjunctions and disjunctions. For an idea of what is allowed, you can examine the relevant code here.

    The SQLFORM.grid advanced search widget generates queries that are ultimately parsed by smart_query, so to get a better idea of how to generate such queries, try creating a test SQLFORM.grid and play with the search widget in the UI to see the queries it generates.