英文:
Two fields with same name causing problem in pydantic model classes
问题
class SnowflakeTable(BaseModel):
database: str
schema: str
table: str
table_schema: List[SnowflakeColumn]
class DataContract(BaseModel):
schema: List[OpenmetadataColumn]
英文:
I have two Pydantic
model classes where two fields have the same name as can be seen below:
class SnowflakeTable(BaseModel):
database: str
schema: str
table: str
table_schema: List[SnowflakeColumn]
class DataContract(BaseModel):
schema: List[OpenmetadataColumn]
These model classes have been integrated with other modules to run via FastAPI
and Mangum
. Now, when I try hitting the APIs it gives me the below error:
NameError: Field name "schema" shadows an attribute in parent "BaseModel"; you might want to use a different field name with "alias='schema'".
So, to resolve this I tried using Field
of Pydantic as below but it didn't work either.
class SnowflakeTable(BaseModel):
database: str
schema: str = Field(..., alias='schema')
table: str
table_schema: List[SnowflakeColumn]
class DataContract(BaseModel):
schema: List[OpenmetadataColumn] = Field(..., alias='schema')
The error remains the same. I tried multiple things w.r.t Fields. Also, tried using Route API but nothing worked. What am I missing here? TIA
P.S. I can't rename the attributes. Thats against the API rules here.
答案1
得分: 1
你需要更改变量名称,因为这些名称已经被pydantic使用了。尝试:
class SnowflakeTable(BaseModel):
database: str
my_var_schema: str = Field(..., alias='schema')
table: str
table_schema: List[SnowflakeColumn]
class DataContract(BaseModel):
my_var_schema: List[OpenmetadataColumn] = Field(..., alias='schema')
不要担心API字段,如果你的字段有一个别名,那么fastapi在请求和响应中会使用别名中的字段名。
更多信息请参考:
https://docs.pydantic.dev/latest/usage/model_config/#alias-precedence
英文:
You have to change the variable names because those names are already in use by pydantic. Try:
class SnowflakeTable(BaseModel):
database: str
my_var_schema: str = Field(..., alias='schema')
table: str
table_schema: List[SnowflakeColumn]
class DataContract(BaseModel):
my_var_schema: List[OpenmetadataColumn] = Field(..., alias='schema')
Don't worry about API fields, if your field has an alias, then fastapi uses the field name in the alias in requests and responses.
More about it:
https://docs.pydantic.dev/latest/usage/model_config/#alias-precedence
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论