Skip to content

Commit

Permalink
Merge pull request #1028 from caarmen/add-pydantic2-blueprint
Browse files Browse the repository at this point in the history
Add a blueprint for pydantic 2
  • Loading branch information
tfranzel authored Jul 17, 2023
2 parents fa568ce + 5a02f01 commit b7f79b7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
8 changes: 7 additions & 1 deletion docs/blueprints.rst
Original file line number Diff line number Diff line change
Expand Up @@ -155,4 +155,10 @@ Pydantic
Preliminary support for `Pydantic <https://github.com/pydantic/pydantic>`_ models. This may or may not
end up in the main package. Catches decorated Pydantic classes and integrates their schema.

.. literalinclude:: blueprints/pydantic.py
Pydantic 1:

.. literalinclude:: blueprints/pydantic.py

Pydantic 2:

.. literalinclude:: blueprints/pydantic2.py
29 changes: 29 additions & 0 deletions docs/blueprints/pydantic2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from drf_spectacular.extensions import OpenApiSerializerExtension
from drf_spectacular.plumbing import ResolvedComponent

from pydantic.json_schema import model_json_schema


class PydanticExtension(OpenApiSerializerExtension):
target_class = "pydantic.BaseModel"
match_subclasses = True

def get_name(self, auto_schema, direction):
return self.target.__name__

def map_serializer(self, auto_schema, direction):

# let pydantic generate a JSON schema
schema = model_json_schema(self.target, ref_template="#/components/schemas")

# pull out potential sub-schemas and put them into component section
for sub_name, sub_schema in schema.pop("definitions", {}).items():
component = ResolvedComponent(
name=sub_name,
type=ResolvedComponent.SCHEMA,
object=sub_name,
schema=sub_schema,
)
auto_schema.registry.register_on_missing(component)

return schema

0 comments on commit b7f79b7

Please sign in to comment.