pydantic model dynamic field data type

7.8k views Asked by At

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?

1

There are 1 answers

3
alex_noname On

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