How does web2py query expressions work?
Asked Answered
S

3

5

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?

Stanleigh answered 2/3, 2012 at 21:37 Comment(0)
C
7

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.

Cheryle answered 2/3, 2012 at 22:22 Comment(0)
H
2

Any operator applied to custom (non-built-in) objects based on evaluation of special methods. It's widely known as operator overloading. So basically field class definition looked alike:

class DBField(...):
#...

   def __gt__(self,value):
      #building query object, based on value
      return query
Hiding answered 2/3, 2012 at 21:51 Comment(0)
S
2

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).

Sip answered 2/3, 2012 at 21:52 Comment(3)
Link down. ____Teryn
@Scoot, What's gluon anywayTeryn
gluon is the package(?) name for all of the web2py code. Here's a more current link: web2py.readthedocs.io/en/latest/_modules/index.htmlSip

© 2022 - 2024 — McMap. All rights reserved.