Skip to content

enable GenericModel duck-typed serialization #1613

@tmchartrand

Description

@tmchartrand

See https://docs.pydantic.dev/latest/concepts/serialization/#serializing-with-duck-typing

Fields of type GenericModel should be able to be initialized with an instance of a subclass model and have all fields serialized. Currently the model must be dumped before initialization:

contains_model=Bar(bar="baz", foo=2).model_dump(),

There's currently a note in GenericModel about this and using extra="allow" in the meantime, which doesn't fully solve the problem.

It seems we could either:

  • replace uses of GenericModel as a field type annotation with GenericModelType=SerializeAsAny[GenericModel]
  • override GenericModel.model_dump_json to have serialize_as_any=True by default

slightly different behavior, don't think I have a preference.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions