Some of the information here may be outdated, please check the book instead

Consider the following web2py model:

   db.Field('title', length=200, requires=IS_NOT_EMPTY()),
   db.Field('author', db.auth_user, if auth.user else None),
   db.Field('body', 'text'),
   db.Field('published_at', 'datetime',,writable=False),
   db.Field('is_draft', 'boolean', default=True),
   db.Field('is_deleted', 'boolean', default=False))

Normally a query looks like


It is possible to name queries (also called "named scopes"):

published =
deleted =
published_and_deleted = published & deleted

and use them in queries

rows = db(published).select()
rows = db(deleted).select()
rows = db(published & deleted).select()
rows = db(published_and_deleted).select()
rows = db(published & deleted)(<
rows = db(published & deleted)('%test%')).select()

Named scopes can be complex and involve multiple tables via implicit joins. For example:

authors =

and now we can select the first name of all users who have an account (in auth_user), who are authors of a post, and their first name starts with 'A'):

rows = db(authors)('A%')).select(db.auth_user.first_name)

Named Scopes in web2py have been available since version 1.0 in October 2007.

© 2008-2010 by Massimo Di Pierro - All rights reserved - Powered by web2py - design derived from a theme by the earlybird
The content of this book is released under the Artistic License 2.0 - Modified content cannot be reproduced.