Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does web2py query expressions work?

Tags:

python

web2py

I just recently had a chance to take a look at web2py framework and although I have some prior experience with Django and more so with plain Python, I couldn't make sense out of the Query system that web2py employs.

Let's take this example from web2py book

db = DAL('sqlite://storage.db')
myquery = (db.mytable.myfield > 'A')
myset = db(myquery)
rows = myset.select()
for row in rows:
    print row.myfield

In a SO comment web2py author says that (db.mytable.myfield > 'A') does not evaluate to True/False directly and it's actually evaluated for each row at the time of selection. I understand this is what allows these expressions to be used as query objects and even be combined.

I've tried to find an answer to this online but couldn't, so here is my question: How is those query expressions are not evaluating to True/False right away? Why is value of myquery is not, say, True? What Python feature that I'm probably missing allows this to work?

like image 736
ntpl Avatar asked Mar 02 '12 21:03

ntpl


2 Answers

The other answers have it, but just to provide a little more web2py-specific detail:

db.mytable.myfield > 'A'

db.mytable.myfield is an instance of the web2py DAL Field class, which inherits from the DAL Expression class. The Expression class itself overloads a number of Python operators, such as ==, <, >, etc. These overloaded operators, when applied to Expression (and therefore Field) objects return an instance of the DAL Query class rather than a standard Python boolean object. Here is the source code for the > (__gt__) operator.

See here for more on operator overloading in Python.

like image 79
Anthony Avatar answered Sep 22 '22 17:09

Anthony


db.mytable.myfield is a gluon.sql.SQLField, which overrides the __gt__ method, so that the expression using the > operator results in a gluon.sql.SQLQuery when evaluated (see http://www.web2py.com/examples/static/epydoc/web2py.gluon.dal.Expression-class.html).

like image 28
Scott Hunter Avatar answered Sep 25 '22 17:09

Scott Hunter