两个具有相同名称的字段在pydantic模型类中引发问题。

huangapple go评论80阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月20日 17:59:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定