field_1
must be 0 by default, but not allowed with field_2
. My try:
from cerberus import Validator
schema = {
'value_1': {
'type': 'integer',
'default': 0
},
'value_2': {
'type': 'integer',
'excludes': ['value_1', ]
}
}
v = Validator(schema)
for doc in [{}, {'value_2': 1}, {'value_2': 1, 'value_2': 1}]:
if not v.validate(doc, schema):
print(v.errors)
else:
print(v.normalized(doc))
I got:
{'value_1': 0}
{'value_2': ["'value_1' must not be present with 'value_2'"]}
{'value_2': ["'value_1' must not be present with 'value_2'"]}
I want to validate second document without errors with normalized result {'value_1': 0, 'value_2': 1}
. How can I achieve the desired result?
EDIT More clear explanation of my goals:
- I want to raise error if value_1
and value_2
exists in incoming document, but set 0
to value_1
if this key not exists in document.
- I want to do it inside cerberus validation/normalization procedure and want to solve it by changing validation schema or validator
Quick Answer (TL;DR)
Detailed Answer
Context
Problem
Solution
Rationale
Example
One schema provides the default values, the other does the validation
Output result
This is just upon understanding your requirement. And this works.
Result: