Reputation: 1006
Pydantic model for compulsory field with alias is created as follows
class MedicalFolderUpdate(RWModel):
id : str = Field(alias='_id')
university : Optional[str]
How to add optional field university's alias name 'school' as like of id?
Upvotes: 6
Views: 7919
Reputation: 585
It is not documented on the Pydantic website how to use the typing Optional with the Fields Default besides their allowed types in which they include the mentioned Optional:
Optional[x] is simply shorthand for Union[x, None]; see Unions below for more detail on parsing and validation and Required Fields for details about required fields that can receive None as a value.
for that, you would have to use their field customizations as in the example:
class Figure(BaseModel):
name: str = Field(alias='Name')
edges: str = Field(default=None, alias='Edges')
without the default value, it breaks because the optional does not override that the field is required and needs a default value. Which is the solution I used to overcome this problem while using Pydantic with fast API to manage mongo resources
Upvotes: 13
Reputation: 11
Try the following:
class MedicalFolderUpdate(RWModel):
id : str = Field(alias='_id')
university : Optional[str] = Field(alias='school')
Upvotes: 1
Reputation: 12008
In your case, you will want to use Pydantic's Field
function to specify the info for your optional field. Also, must enable population fields by alias by setting allow_population_by_field_name
in the model Config
:
from typing import Optional
class MedicalFolderUpdate(BaseModel):
id: str = Field(alias='_id')
university: Optional[str] = Field(alias="school")
class Config:
allow_population_by_field_name = True
By default, value for university
will be None
. If you want to exclude unset values, you can do so when serializing to json or dict like so:
raw_data = {"id": "abc"}
row = MedicalFolderUpdate.parse_obj(raw_data)
# default, university is None
print(row.dict()) # {'id': 'abc', 'university': None}
# exclude from serialization
print(row.dict(exclude_unset=True)) # {'id': 'abc'}
Upvotes: 0