python - Pydantic 场没有值(value)

标签 python pydantic

在尝试命名 Pydantic 字段架构时,我收到以下错误:

NameError: Field name "schema" shadows a BaseModel attribute; use a different field name with "alias='schema'".

已关注 the documentation ,我尝试使用别名来避免冲突。请参阅下面的代码:

from pydantic import StrictStr, Field
from pydantic.main import BaseModel    

class CreateStreamPayload(BaseModel):
          name: StrictStr
          _schema: dict[str: str] = Field(alias='schema')

尝试通过以下方式实例化 CreateStreamPayload 时:

a = CreateStreamPayload(name= "joe",
            _schema= {"name": "a name"})

生成的实例只有一个name值,没有其他值。

a.dict()
{'name': 'joe'}

这对我来说完全没有意义,有人可以解释一下发生了什么吗?

非常感谢

最佳答案

来自the documentation :

Class variables which begin with an underscore and attributes annotated with typing.ClassVar will be automatically excluded from the model.

一般来说,附加下划线以避免冲突,因为前导下划线被视为 dunder(魔术)成员或私有(private)成员:_schemaschema_

关于python - Pydantic 场没有值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73828037/

相关文章:

python - ImageData 生成器中的 validation_split 返回 0 个图像

python - 如何在名称中带有连字符的 FastApi-SwaggerUI 中键入变量?

python - 如果 BaseModel 获得意外参数,如何使 pydantic 引发 ValidationError

python - 为大型嵌套父级、子级复杂 JSON 文件创建 Pydantic 模型

python - 布洛赫球上的实时绘图

python - 如何在python中的多个线程之间正确共享信息?

python - Django 管理内联更改列表

python - 狂妄自大的 : duplicate validator function

python-3.x - 如何更改 Pydantic 默认 __root__ 示例

python - Editra 0.7.08 是可靠的 IDE 吗?