在尝试命名 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'}
这对我来说完全没有意义,有人可以解释一下发生了什么吗?
非常感谢
最佳答案
Class variables which begin with an underscore and attributes annotated with
typing.ClassVar
will be automatically excluded from the model.
一般来说,附加下划线以避免冲突,因为前导下划线被视为 dunder(魔术)成员或私有(private)成员:_schema
➡ schema_
关于python - Pydantic 场没有值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73828037/