2

I am currently working on a page where a user would select all the appropriate fields in a search form (html) which would than pass the values to the web2py query.

I am having an issue with writing this query? I am wondering how to actually pass the values from HTML form to the web2py query to be run against the database?

1 Answer 1

2

When you submit a form to web2py (via GET or POST), all the form variables will be available in request.vars (for more on this, see the book sections on Dispatching and the request object as well as the chapter on forms).

So, you could do something like:

def search():
    rows = None
    if request.vars:
        query = reduce(lambda a, b: (a & b),
            (db.mytable[var] == request.vars[var] for var in request.vars))
        rows = db(query).select()
    return dict(rows=rows)

Note, the reduce() with the generator expression is equivalent to writing a query like this:

(db.mytable.field1 == request.vars.field1) & \
(db.mytable.field2 == request.vars.field2) & \
...
(db.mytable.fieldN == request.vars.fieldN)
Sign up to request clarification or add additional context in comments.

2 Comments

Hi thanks for the reply, however I am still a bit confused as to what you've done there.. what does query = reduce(lambda a, b: (a & b) mean?
It just takes a list of queries and joins them with the & logical operator. reduce is a Python function, so you can probably find online resources explaining its use. That bit of code is not web2py specific -- just a shortcut way of creating the query without having to write it all out manually (as shown in the last section of code).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.