Discussion:
[FE-discuss] ForEach access to parent validators?
Jason Yamada-Hanff
2009-02-27 14:43:09 UTC
Permalink
Hi all,

I am trying to build a validator for checking unique constraints in
the db. For this, I'd like access to the parent validator's field
dictionary from within a nested validator. Is this possible?

A simple case: let's say I have two models with a one-to-many
relationship::

Person
------
id
name

Phone
-----
id
person_id <fk: person.id> <UNIQUE #1>
number <UNIQUE #1>

Phone has a compound unique constraint like (person_id, number).

The FormEncode schemas might look like this::

class PhoneValidator(FancyValidator):
id = Int()
number = String()

class PersonValidator(FancyValidator):
allow_extra_fields = True
filter_extra_fields = True
pre_validators = [variabledecode.NestedVariables()]
id = Int()
phone = ForEach(PhoneValidator())

With this sort of scheme, I was hoping to just add a unique-ness
validator to chained_validators on the PhoneValidator. To do actually
validate the constraint (person_id, number), though, I need to access
the value of `id` in PersonValidator from within the PhoneValidator
(within ForEach). Adding a a `person_id` field to PhoneValidator
feels like a messy hack, since that information is already available
from the parent validator.

What is the best way to approach this with FormEncode? I could place
the unique-ness check on chained_validators under PersonValidator, but
then don't I lose the ease of the ForEach wrapper?

Thanks,
Jason
Ian Bicking
2009-03-04 05:16:12 UTC
Permalink
Sorry for the late response...
Post by Jason Yamada-Hanff
I am trying to build a validator for checking unique constraints in
the db.  For this, I'd like access to the parent validator's field
dictionary from within a nested validator.  Is this possible?
It is possible. I think a chained validator would probably be more
appropriate for your particular case, but you can also get access to
the other values. The state object will have attributes assigned to
it, if you don't pass in None (which is the default, though might not
be if you are using a framework). The full dictionary will then be in
state.full_dict (Schema will just assign the full_dict attribute on
whatever object gets passed in).
--
Ian Bicking | http://blog.ianbicking.org
Loading...