-
Notifications
You must be signed in to change notification settings - Fork 270
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
36 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |