Equivalance of `required=True` and `IS_NOT_IN_DB` in web2py's pyDAL

392 Views Asked by At

The web2py book gives an example of modelling an image blog. The lines of code relevant to my question are:

db.define_table('image',
                Field('title', unique=True),
                Field('file', 'upload'),
                format = '%(title)s')

db.image.title.requires = IS_NOT_IN_DB(db, db.image.title)

The text states that expressions like db.image.title.requires are validators. But

  1. It does not make it clear whether unique=True in the expresssion Field('title', unique=True) is also a validator with the exact same functionality
  2. What impact a validator has on database-driven form generation.
1

There are 1 best solutions below

0
Anthony On BEST ANSWER

From the book:

Notice that requires=... is enforced at the level of forms, required=True is enforced at the level of the DAL (insert), while notnull, unique and ondelete are enforced at the level of the database. While they sometimes may seem redundant, it is important to maintain the distinction when programming with the DAL.

unique=True does not result in a validator being created. It results in a UNIQUE constraint being added to the database schema when web2py first creates the table in the database (assuming you have enabled migrations). If you call the DAL .insert() or .update() methods with values that would violate this constraint, the database will throw an error (which will result in a Python exception in your app).

Setting requires=IS_NOT_IN_DB(...) creates a validator, which will be run when you (a) submit a form created using SQLFORM or (b) call the DAL .validate_and_insert() or .validate_and_update() methods. If validation fails, the insert/update is not sent to the database at all, and you do not get a Python exception, but simply a record of the failure (which is typically displayed on the form in the case of a form submission).

If you will be making inserts and updates via forms, it is a good idea to use the validator, because it provides the proper user experience (i.e., displaying an error message with the form). It is also a good idea to set unique=True so the database has the appropriate schema, in case you make inserts/updates via means other than forms (and possibly even outside of web2py or the DAL).