I wrote this function, to help out with a project I'm working on, that
has an extensive use of the common filter functionality (describes in
chapter 6 of the web2py book).
Say you have a blog, containing active, and inactive posts:

db.define_table('post',
 Field('subject'),
 Field('post','text'),
 Field('is_active','boolean'),
 common_filter = lambda query: db.post.is_active == True
)

And we have comments on posts:
db.define_table('comment',
 Field('post',db.post),
 Field('comment','text')
)

Running db(db.comment.id > 0).select(), will select all comments,
including those posts where is_active is False.

Solution:
use this function in a model, module, whatever:

def inherit_common_filter(db, col):
    ''' gets the common filter of a field refrenced
    '''
    ref_table_name = col.type.replace('reference ', '')
    ref_table = db[ref_table_name]
    ref_table_filter = ref_table._common_filter

    return lambda query:
col.belongs(db(ref_table_filter(query))._select(ref_table.id))

Now, the new model looks like:
db.define_table('comment',
 Field('post',db.post),
 Field('comment','text')
)
db.comment._common_filter = inherit_common_filter(db, db.comment)

Now Running db(db.comment.id > 0).select(), will select all comments
that are set to is_active == True.

Hope you'll find this useful

Reply via email to