How to create Generic Schema for openapi? #817
Answered
by
vitalik
hushoujier
asked this question in
Q&A
-
I have the following piece of code, but there is a problem with openapi page, how should I solve it? Code environment : from typing import TypeVar, Generic, List
from django.http import HttpRequest
from ninja import Router, Query, Schema
from pydantic import Field
T1 = TypeVar('T1')
T2 = TypeVar('T2')
router = Router()
class Params(Schema):
name: str
age: int = Field(0, ge=0, le=120)
class Response(Schema, Generic[T1, T2]):
code: int
data: T1
message: T2
class Data(Schema):
a: int
b: List[str]
@router.get('demo/', response=Response[Data, str])
def list_level(request: HttpRequest, params: Params = Query(...)):
return {
'code': 200,
'data': {'a': 1, 'b': ['a', 'b', 'c']},
'message': 'good'
} So,How should I make the openapi page's 200 response look like this: {
"code": 0,
"data": {
"a": 0,
"b": [
"string",
"string",
"..."
]
},
"message": "string"
} |
Beta Was this translation helpful? Give feedback.
Answered by
vitalik
Aug 8, 2023
Replies: 1 comment
-
Hi @suuperhu in pydantic 1.xx you should use special from pydantic.generics import GenericModel
...
class Response(GenericModel, Generic[T1, T2]):
code: int
data: T1
message: T2 next release django ninja will support pydanitc2 - where you do not need to GenericModel |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
hushoujier
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @suuperhu
in pydantic 1.xx you should use special
GenericModel
- refnext release django ninja will support pydanitc2 - where you do not need to GenericModel