There might be a way to enforce this at the database level, but one of
the more experienced members will have to address that.
What I can offer, is something I've done several times to apply custom
validation at the form level.
In the controller create the form using the onvalidation method.
d['form']=crud.create(db.dog,onvalidation=validate_new_dog)
Then define
def validate_new_dog(form):
"""
Validates unique dog name per user
"""
if db(db.dog.id==form.vars.owner)
(db.dog.name==form.vars.name).count() > 0:
form.errors.name = "This owner already has a dog of this name"
return
Warning, I haven't tested this code so it could contain a typo. For
example form.vars.owner *might* need to be wrapped in str() I'm not
sure if that's going to return a reference object.
I think this also has the side effect of a user submitting two forms
at the same time and both submitting. Hasn't stopped me from using
it, just something to know is a possibility.
On Aug 5, 12:56 pm, Christian <[email protected]> wrote:
> Hi,
>
> I have a pretty simple model, which is very similar to one commonly
> referenced in the web2py book:
>
> db.define_table('person',
> Field('name', requires=IS_NOT_EMPTY()))
> db.define_table('dog',
> Field('owner', db.person),
> Field('name', requires=IS_NOT_EMPTY()))
>
> db.dog.owner.requires = IS_IN_DB(db,db.person.id,'%(name)s')
>
> Now, what I'm wanting to do is place a restriction on dog names.
> Different dog owners can have dogs of the same name, but no single
> person can own 2 or more dogs of the same name. It's not obvious to me
> how to use IS_IN_DB() to accomplish this, since that will disallow
> different owners from having a common dog name.
>
> The problem that I'm seeing is that when you want to add a new dog to
> the database, you have to have some way of referencing the owner to
> which the dog will belong when you do the validations, so that you can
> check all the dogs that certain owner already owns. I've looked into
> custom validators a bit, but I'm not sure how to do this. Can anyone
> offer some advice on how to accomplish this? Thanks!