Sunday, 26 September 2021

Pydantic: Field aliases

Field aliases are used if you want to follow other naming conventions.

 

Example

class Employee(BaseModel):
    id: int = Field(alias='emp_id')
    name: str = Field(alias='emp_name')
    age: int
    address: Address

We can define the Employee object using alias names like emp_id, emp_name.

 

emp1 = Employee(emp_id = 1, emp_name = 'Ptr', age = 23)

 

You can model the behaviour by passing by_alias argument to the methods.

emp1JsonByAlias = emp1.json(by_alias=True)

 

Find the below working application.

 

field_alias_1.py

 

from pydantic import BaseModel, Field

class Employee(BaseModel):
    id: int = Field(alias='emp_id')
    name: str = Field(alias='emp_name')
    age: int

emp1 = Employee(emp_id = 1, emp_name = 'Ptr', age = 23)

emp1Json = emp1.json()
emp1JsonByAlias = emp1.json(by_alias=True)

print('emp1Json -> ' + emp1Json)
print('emp1JsonByAlias -> ' + emp1JsonByAlias)


Output

emp1Json -> {"id": 1, "name": "Ptr", "age": 23}
emp1JsonByAlias -> {"emp_id": 1, "emp_name": "Ptr", "age": 23}


Note

a.   When creating an instance to a model with aliases, we pass inputs that match the aliases.

b.   You should access the field using the field name (and not the field alias).

c.    When converting the model objects to external format like json, dict, you should pass ‘by_alias’ argument to it.


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment