8

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?

3 Answers 3

13

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

Sign up to request clarification or add additional context in comments.

Comments

1

Try the following:

class MedicalFolderUpdate(RWModel):
    id : str = Field(alias='_id')
    university : Optional[str] = Field(alias='school')

Comments

0

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'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.