Open jmbledsoe opened 1 week ago
The changes there were primarily made to generate better OpenAPI documentation through TypeHints( #1702 ). I didn’t take more complex cases. If you have a better solution, I think submitting a PR would be worth a try. :)
Can you please post here your implementation of your field?
Is your feature request related to a problem? Please describe.
I am using Postgres JSONB columns for storing complex data structures, and I have Pydantic models representing those data structures. Where the column itself is a Pydantic model, I can use
JSONField
to encode and decode the model:model_dump
to convert the model to a Python object here__init__
to construct a model from a Python dictionary hereHowever, some other columns are not themselves Pydantic models but are composite objects that include Pydantic models e.g.
list[SomePydanticModel]
ordict[str, SomePydanticModel]
. I cannot useJSONField
for these columns because the instances themselves are not Pydantic models i.e. they do not have themodel_dump
function and the field type is notModelMetaclass
.Describe the solution you'd like Pydantic provides the
TypeAdapter
class for working with composite objects like this. Itsdump_python
function behaves likemodel_dump
, and itsvalidate_python
function behaves like a model's__init__
function. Using the functions onTypeAdapter
would allowJSONField
to handle composite models in the same way that it handles simple models.Describe alternatives you've considered I currently have an implementation of a Tortoise ORM field that uses
TypeAdapter
. My implementation bypasses theencoder
anddecoder
functions, opting instead to usedump_json
andvalidate_json
directly instead. I intend to open a PR with this implementation, but I'm open to guidance to do something differently to bring this capability into Tortoise ORM.Additional context I am not 100% sure of the performance cost of instantiating
TypeAdapter
, so we may want to include some form of caching constructed instances.