如何影响从 FastAPI 生成的 Pydantic 代码上对 Pydantic 成员名称的处理?

问题描述 投票:0回答:1

当我在 FastAPI (OpenAPI) 中指定 API 和模式并让 FastAPI 生成模式对象/类时,成员名称将采用蛇形大小写格式并获得驼峰大小写的别名。

class ObjectIdentifier(BaseModel):
    """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

    Do not edit the class manually.

    ObjectIdentifier - a model defined in OpenAPI

        location: The location of this ObjectIdentifier.
        location_type: The location_type of this ObjectIdentifier.
    """

    location: str = Field(alias="location")
    location_type: str = Field(alias="locationType")

ObjectIdentifier.update_forward_refs()

但是当我使用 Pydantic 类的构造函数和数据库结果集中的字典填充 Pydantic 类时,字典需要包含使用驼峰式大小写编写的键(属性名称)。

# code that works
object_info = ObjectInformation(
    objectId=ObjectIdentifier(location=location, locationType=location_type),
    objectInfo=object_info
)

# code that does not work
object_info = ObjectInformation(
    object_id=ObjectIdentifier(location=location, location_type=location_type),
    object_info=object_info
)

我可以让生成的 Pydantic 代码使用蛇形属性名称吗?

我尝试了几种在自定义基类中使用

alias_generators
Config
对象的方法,但我无法使用这些方法,因为 Pydantic 代码已生成,而且我尚未弄清楚如何在我的上下文中使用它们。

理想情况下,我可以使用这样的语法:

object_info = ObjectInformation(**database_result)

database_result
像这样:

database_result = dict(
    location: "some location",
    location_type: "some location type",
    object_info: "the important object info"
)

该字典是对 SQL DB 查询的结果,我无法获取驼峰式大小写属性名称,因为数据库访问将每个名称转换为小写。因此,我只能从数据库结果中得到蛇形情况。

注意,Pydantic 结构是嵌套的,

ObjectIdentifier
位于
ObjectInformation
内。我不知道嵌套是否应该像我尝试过的那样工作。

Python:3.9 派丹蒂克:3.10.15

python-3.x openapi pydantic
1个回答
0
投票

将数据库模型(应反映数据库结构)与模式(应反映输入/输出数据格式)分开是更好的做法。如果您想在数据库模型中使用 pydantic,您应该执行以下操作:

class BaseObject(BaseModel):
    # Your fields here


class ObjectSchema(BaseObject):
    # alias_generators / validators / or whatever else related to your API format

class ObjectDb(BaseObject):
    model_config = ConfigDict(from_attributes=True)
    
    ...

但我还建议考虑使用 SQLAlchemy 模型/SQLModel 来管理数据库模型。

© www.soinside.com 2019 - 2024. All rights reserved.