I want to assign field data type dynamically based on specific conditions. Below are my models:
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
So, based on "type" i.e. GCS or ORACLE how do I dynamically change the "details" data type during validation?
Pydantic
could do this without using an additional type
field by means of the Union
type, 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))
Output:
name='' type='GCS' details=GCSDetails(bucket='', folderName='')
name='' type='ORACLE' details=OracleDetails(host='', port=15, user='')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With