pydantic模型动态场数据类型

2024-09-30 22:19:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望根据特定条件动态分配字段数据类型。以下是我的模型:

class Connection(BaseModel):
    name: str
    # type can be GCS or ORACLE
    type: str
    details: GCSDetails/OracleDetails

class GCSDetails(BaseModel):
    bucket: str
    folderName: str

class OracleDetails(BaseModel):
    host: str
    port: int
    user: str

那么,基于“类型”,即GCS或ORACLE,如何在验证期间动态更改“详细信息”数据类型


Tags: name模型typebeconnectioncanclassbasemodel
1条回答
网友
1楼 · 发布于 2024-09-30 22:19:27

Pydantic可以通过Union类型because执行此操作,而无需使用额外的type字段

pydantic will attempt to 'match' any of the types defined under Union and will use the first one that matches.

from typing import Union

from pydantic import BaseModel


class GCSDetails(BaseModel):
    bucket: str
    folderName: str


class OracleDetails(BaseModel):
    host: str
    port: int
    user: str


class Connection(BaseModel):
    name: str
    # type can be GCS or ORACLE
    type: str
    details: Union[GCSDetails, OracleDetails]


test_gcs = {"name": "", "type": "GCS", "details": {"bucket": "", "folderName": ""}}
test_oracle = {"name": "", "type": "ORACLE", "details": {"host": "", "port": 15, "user": ""}}

print(Connection(**test_gcs))
print(Connection(**test_oracle))

输出:

name='' type='GCS' details=GCSDetails(bucket='', folderName='')
name='' type='ORACLE' details=OracleDetails(host='', port=15, user='')

相关问题 更多 >