[ python中使用泛型 ]


泛型TypeVar

我这里是定义数据结构模板, 来限制用户的dict内容

from ninja import Schema
from typing import TypeVar, Generic

T = TypeVar('T')

class ApiResSchema(Schema, Generic[T]):
    data: T = ""
    code: int = 0
    msg: str = ""

django-ninja使用的时候可以通过[]写入类型, 框架自动序列化

@message_router.get(path="/", response=ApiResSchema[List[MessageRespSchema]])
def get_messages(request):
    messages = Message.objects.all()
    return ApiResSchema(data=messages)