Skip to content

Commit 3043aba

Browse files
authored
Populate field name for validation of default value (#1826)
1 parent f5e72c3 commit 3043aba

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

src/validators/model_fields.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,16 +195,16 @@ impl Validator for ModelFieldsValidator {
195195
}
196196
Err(err) => return Err(err),
197197
};
198+
199+
let state = &mut state.rebind_extra(|extra| extra.field_name = Some(field.name_py.bind(py).clone()));
200+
198201
if let Some((lookup_path, value)) = op_key_value {
199202
if let Some(ref mut used_keys) = used_keys {
200203
// key is "used" whether or not validation passes, since we want to skip this key in
201204
// extra logic either way
202205
used_keys.insert(lookup_path.first_key());
203206
}
204207

205-
let state =
206-
&mut state.rebind_extra(|extra| extra.field_name = Some(field.name_py.bind(py).clone()));
207-
208208
match field.validator.validate(py, value.borrow_input(), state) {
209209
Ok(value) => {
210210
model_dict.set_item(&field.name_py, value)?;

tests/validators/test_with_default.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -967,3 +967,38 @@ def test_default_factory_not_called_union_ok(container_schema_builder) -> None:
967967
v = SchemaValidator(schema)
968968
s = SchemaSerializer(schema)
969969
assert s.to_python(v.validate_python({'a': 1}), mode='json') == {'a': 1, 'b': 2, 'c': 3}
970+
971+
972+
def test_default_validate_default_after_validator_field_name() -> None:
973+
class Model:
974+
pass
975+
976+
field_name: str | None = None
977+
978+
def val_func(value, info: core_schema.ValidationInfo):
979+
nonlocal field_name
980+
field_name = info.field_name
981+
return value
982+
983+
schema = core_schema.model_schema(
984+
cls=Model,
985+
schema=core_schema.model_fields_schema(
986+
fields={
987+
'a': core_schema.model_field(
988+
schema=core_schema.with_default_schema(
989+
schema=core_schema.with_info_after_validator_function(
990+
val_func,
991+
schema=core_schema.str_schema(),
992+
),
993+
default='default',
994+
)
995+
)
996+
}
997+
),
998+
config={'validate_default': True},
999+
)
1000+
1001+
val = SchemaValidator(schema)
1002+
val.validate_python({})
1003+
1004+
assert field_name == 'a'

0 commit comments

Comments
 (0)