I begin with marshamallow and I try to validate a field. My schema is very simple.
class MySchema(Schema):
pid = fields.String(required=true)
visibility = fields.String(validate=OneOf(['public','private'])
@validates('visibility')
def visibility_changes(self, data, **kwargs):
# Load data from DB (based on ID)
db_record = load_data_from_db(self.pid) # <-- problem is here
# Check visibility changed
if db_record.get('visibility') != data:
do_some_check_here()
But using self.pid
doesn't work. It raises an error AttributeError: 'MySchema' object has no attribute 'pid'
.
What's the correct way to access to my "pid" field value into my @validates
function ?
I tried using self.fields
, self.load_fields.get('pid').get_value()
, ... no easy way to access it, but I suppose that Marshmallow has such magic method.
Thanks for your help.
You should use @validates_schema
to define a validator that works on several fields. It takes the whole input payload as argument so you can find pid in there.