gpt4 book ai didi

python - pydantic 模型动态字段数据类型

转载 作者:行者123 更新时间:2023-12-04 03:51:45 77 4
gpt4 key购买 nike

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

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,我如何在验证期间动态更改“详细信息”数据类型?

最佳答案

Pydantic 无需使用额外的 type 字段即可通过 Union 类型做到这一点,because

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='')

关于python - pydantic 模型动态字段数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64365784/

77 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com