首页 > 解决方案 > 声明 Pydantic 模型“TypeError:‘type’对象不可迭代”

问题描述

我正在使用 FastAPI 构建数据 API。我希望客户发布 2 个 24 个浮点数的列表,稍后我将它们保存到数据库中。

当我尝试创建 Pydantic 模型时:

from pydantic import BaseModel

class Prices(BaseModel):
    buying_price: list(float)=[]
    selling_price: list(float)=[]

我收到以下错误:

File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 3, in <module>
    class Prices(BaseModel):
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 4, in Prices
    buying_price: list(float)=[]
TypeError: 'type' object is not iterable

即使错误是不言自明的,我也不明白。

然后,查看文档,我发现了以下方式:

from pydantic import BaseModel
from typing import List

class Prices(BaseModel):
    buying_price: List(float)=[]
    selling_price: List(float)=[]

但我收到以下错误。

File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 4, in <module>
    class Prices(BaseModel):
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 5, in Prices
    buying_price: List(float)=[]
File "C:\Users\Amin y Lubna\anaconda3\lib\typing.py", line 727, in __call__
    raise TypeError(f"Type {self._name} cannot be instantiated; "
TypeError: Type List cannot be instantiated; use list() instead

几天来我一直在努力解决这个错误,但我无法找到解决问题的方法。

标签: pythonlistfastapipydantic

解决方案


你需要使用list[float],而不是list(float)


推荐阅读