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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With