在 Pydantic 中添加比模型更多的字段,该字段依赖于另一个字段值

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

我对 fastAPI 非常陌生,我正在尝试在 pydantic 基本模型中复制 Django models.SerializerMethodField() ,就像在 Django 中我们可以做的那样


class A(serailizer.Serializers):
    service = serializer.SerializerMethodField()

    def get_service(self, instance):
        return "option1" if instance.some_field else "option2"

所以,我正在使用 pydantic v2,并且我按照以下方式执行此操作

class ConnectorRead(TimeStampedBaseModel, ConnectorBase):
    connector_id: int
    service: ConnectorService = None

    class Config:
        # orm_mode = True  # it has been changed in v2
        from_attributes = True

    @field_serializer("service")
    def get_service(self, value) -> ConnectorService:
        return ConnectorService.INTERNAL if self.function_name else ConnectorService.EXTERNAL

这种方法正确还是我们有其他方法可以做到这一点?我查了一下,但找不到足够的资源来理解它。

我的路由器代码如下

@router.get("/", response_model=List[ConnectorRead])
def list_connectors(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    connectors = db.query(Connector).offset(skip).limit(limit).all()
    return connectors

如您所见,我直接使用response_model来序列化我的模型对象。

提前致谢。

python fastapi pydantic-v2
1个回答
0
投票

你想要的是一个计算字段

from pydantic import computed_field


class ConnectorRead(TimeStampedBaseModel, ConnectorBase):
    connector_id: int

    class Config:
        from_attributes = True

    @computed_field
    @property
    def service(self) -> ConnectorService:
        return ConnectorService.INTERNAL if self.function_name else ConnectorService.EXTERNAL
© www.soinside.com 2019 - 2024. All rights reserved.