Skip to content

Commit

Permalink
fix(pydantic): allow pydantic model instances as defaults (jpmorganch…
Browse files Browse the repository at this point in the history
  • Loading branch information
dada-engineer committed Mar 8, 2024
1 parent 40687f5 commit 96ad35e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/py_avro_schema/_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,7 @@ def _record_field(self, py_field: dataclasses.Field) -> RecordField:
default=default,
options=self.options,
)

return field_obj


Expand Down Expand Up @@ -899,6 +900,9 @@ def _record_field(self, name: str, py_field: pydantic.fields.FieldInfo) -> Recor
docs=py_field.description or "",
options=self.options,
)
# allow to use pydantic models as default values
if PydanticSchema.handles_type(default.__class__):
field_obj.default = default.model_dump(mode="json") # type: ignore
return field_obj

def _annotation(self, field_name: str) -> Type:
Expand Down
25 changes: 25 additions & 0 deletions tests/test_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,3 +523,28 @@ class PyType(Base):
],
}
assert_schema(PyType, expected)


def test_base_model_defaults():
class Default(pydantic.BaseModel):
field_a: str = "default_a"

class PyType(pydantic.BaseModel):
default: Default = pydantic.Field(..., default_factory=Default)

expected = {
"fields": [
{
"default": {"field_a": "default_a"},
"name": "default",
"type": {
"fields": [{"default": "default_a", "name": "field_a", "type": "string"}],
"name": "Default",
"type": "record",
},
}
],
"name": "PyType",
"type": "record",
}
assert_schema(PyType, expected)

0 comments on commit 96ad35e

Please sign in to comment.