python Pydantic AttributeError:'FieldInfo'对象没有属性'bodyKey'

ep6jt1vc  于 11个月前  发布在  Python
关注(0)|答案(1)|浏览(317)

我正在尝试运行的代码:

from typing import ClassVar
from pydantic import BaseModel, Field

class IndexSchema(BaseModel):
    bodyKey: str = Field(..., description="Body Key in the data")

class Index(BaseModel):
    name: str = Field(..., description="Name of the index")
    schema: ClassVar[IndexSchema] = Field(..., description="schema of the data")

obj = Index(name="Rom",schema=IndexSchema(bodyKey="Rom is crazy"))
print(obj.name)
print(obj.schema.bodyKey)

字符串
尝试运行此代码时,出现以下错误

Rom
Traceback (most recent call last):
  File "/Users/rommonda/Desktop/Llama/test.py", line 15, in <module>
    print(obj.schema.bodyKey)
AttributeError: 'FieldInfo' object has no attribute 'bodyKey'


有什么办法能让我们和好吗?
PS:使用ClassVar[],因为BaseModel也有一个名为'schema'的属性,所以它会出错

km0tfn4u

km0tfn4u1#

Pydantic在运行时覆盖此字段。
如果你只需要这个字段名来进行序列化,那么你可以使用alias

from pydantic import BaseModel, Field

class IndexSchema(BaseModel):
    bodyKey: str = Field(..., description="Body Key in the data")

class Index(BaseModel):
    name: str = Field(..., description="Name of the index")
    index_schema: IndexSchema = Field(..., description="schema of the data", alias="schema")

obj = Index(name="Rom", index_schema=IndexSchema(bodyKey="Rom is crazy"))
print(obj.name)
print(obj.index_schema.bodyKey)

obj2 = Index.model_validate({"name": "Rom", "schema": {"bodyKey" : "Rom is crazy"}})

print(obj2.name)
print(obj2.index_schema.bodyKey)

字符串
我现在不能运行和检查这段代码,但它应该可以工作

相关问题