If you can't understand the code, just try it: web2py.py -M -S mytestapp
db.define_table( 'tests', Field('uniquefield', unique=True), Field('withvalidator', requires=IS_NOT_IN_DB(db, 'tests.withvalidator')) ) >>> ret = db.tests.validate_and_insert(uniquefield='a', withvalidator='b') >>> ret <Row {'errors': <Row {}>, 'id': 1}> >>> ret = db.tests.validate_and_insert(uniquefield='a', withvalidator='b') >>> ret <Row {'errors': <Row {'uniquefield': 'value already in database or empty', 'withvalidator': 'value already in database or empty'}>, 'id': None}> >>> ret = db(db.tests.uniquefield=='a').validate_and_update(withvalidator= 'b') >>> ret <Row {'updated': None, 'errors': <Row {'withvalidator': 'value already in database or empty'}>}> >>> ret = db(db.tests.uniquefield=='a').validate_and_update(withvalidator= 'c') >>> ret <Row {'errors': <Row {}>, 'update': 1}> So, just as stated into the book, you have: ret.errors that holds all errors if some costraint isn't fullfilled (and there is an error for every field that has an error, so multiple errors can be returned) ret.id with the id of the newly inserted record ret.update with the number of lines actually updated. PS: if you have 5 unique fields, the only way to validate them (before inserting or updating) all is firing 5 different queries ( DAL does "under the hood" this by default with unique (it gets by default a "IS_NOT_IN_DB validator"), IS_IN_DB and IS_NOT_IN_DB validators). On Monday, July 23, 2012 9:27:37 PM UTC+2, tiadobatima wrote: > > > Hi guys, > > I'm trying to understand what validate_and_insert() > and validate_and_update() are doing to see if I can use it reliably. > I'm writing an API, and I have no need for form validation. So after > spending sometime reading the DAL code, I still have a few questions: > > - When I insert a record that already exists (unique field), > validate_and_insert() is smart enough to tell me that the record already > exist, but I can't figure out how? I can't find out which "select" > statement it's doing. > - If the validation is per-field, and the table has 5 "unique" fields, > will DAL make 5 selects before inserting? > - Is it possible to get more than one error in return dict from > validate_and_insert() ret.errors? > - What people are using for DAL/DB layer validations on rest APIs? From my > google searches, it looks like not a lot of people are using > validate_and_insert(). > > Thanks! :) > --