I set a field in a table definition to "unique = True".

I then tested this and deliberately entered a duplicate value.  The
result was an error ticket:

76.22.75.122.2012-02-08.23-48-55.c324e160-1b8e-4db0-9345-5422e59467c2

<class 'psycopg2.IntegrityError'> duplicate key value violates unique
constraint "category_name_key" DETAIL: Key (name)=(Religious) already
exists.
VERSION

This is a bit unfortunate as this is a very likely runtime error as a
site visitor might not realize his entry was a duplicate.

I went back and added a constraint on the field:

jodb.category.name.requires = IS_NOT_IN_DB(jodb,jodb.category.name)

I went back and added a deliberate duplicate and the error was trapped
when the form was submitted, which was the right behavior (though the
message isn't that pretty!).

I only point this out because the web2py book says that adding the
constraint is "optional" when a field has been set to unique.  Well,
it's not really optional if you don't want your users seeing a runtime
error:

In line 14, db.image.title represents the field "title" of table
"image". The
attribute requires allows you to set requirements/constraints that
will be
enforced by web2py forms. Here we require that the "title" is unique:
IS_NOT_IN_DB(db, db.image.title)
Notice this is optional because it is set automatically given that
Field(’title’,
unique=True).

I think these two specifications do two different things.  Setting the
field to unique tells the DAL to tell the db to make the field values
unique in the DDL.

Setting the constraint tells web2py to enforce uniqueness in CRUD.

You need to do both.

Reply via email to