如何创建带count字段的泛型列表Pydantic模型
问题说明
需要实现Pydantic模型校验如下结构的数据:
{ "count": <int>, "items": [...] }
要求items列表内的元素支持任意自定义Pydantic模型类型。
初始泛型实现代码如下:
from typing import TypeVar, Generic, List from pydantic import BaseModel T = TypeVar("T") class CountList(BaseModel, Generic[T]): items: List[T] count: int
实际使用时传入其他Pydantic模型作为泛型参数解析数据,items字段返回结果为字典,而非对应模型实例对象。
解决方法
出现该问题的核心原因是使用泛型模型时没有显式指定泛型的具体类型参数,Pydantic无法感知items列表内的元素需要转换为哪类模型实例,只能保留原始字典结构。
正确用法示例
- 先定义
items对应的业务模型,比如用户模型:
class User(BaseModel): id: int username: str
- 解析数据时,显式将具体模型作为泛型参数传入
CountList:
raw_data = { "count": 2, "items": [ {"id": 1, "username": "zhangsan"}, {"id": 2, "username": "lisi"} ] } # Pydantic v2 写法 result = CountList[User].model_validate(raw_data) # Pydantic v1 写法 # result = CountList[User].parse_obj(raw_data)
此时result.items内的元素会被自动转换为User类实例,可以直接调用模型的属性、方法。
优化类型约束
如果要强制泛型参数T必须是Pydantic模型子类,可以在定义TypeVar时添加bound参数,从类型检查阶段拦截非法类型传入:
# 约束T必须是BaseModel的子类 T = TypeVar("T", bound=BaseModel) class CountList(BaseModel, Generic[T]): items: List[T] count: int
嵌套使用注意
如果CountList作为其他Pydantic模型的字段使用,同样需要显式指定泛型参数,否则仍然会返回字典:
# 错误写法:未指定泛型参数 class Resp(BaseModel): data: CountList # 正确写法:绑定具体模型类型 class Resp(BaseModel): data: CountList[User]
内容的提问来源于stack exchange,提问作者Amirfel
相关产品推荐
相关产品推荐

