Monday, 20 September 2021

Pydantic: construct: Create models without validation

‘construct’ is a class method, used to create model without validaton.

 

When should I use this method?

This method can be used, when data is already validated and you want to create a model as efficiently as possible.

 

Example

emp1Construct = Employee.construct(**emp1Dict)

 

Find the below working application.

 

construct_1.py

from pydantic import BaseModel

class Employee(BaseModel):
    id: int
    name: str
    age: int

emp1 = Employee(id = 1, name = 'Krishna', age = 23)
emp1Dict = emp1.dict();

emp1Construct = Employee.construct(**emp1Dict)

print('emp1 -> ' + str(emp1))
print('emp1Dict -> ' + str(emp1Dict))
print('emp1Construct -> ' + str(emp1Construct))

 

Output

emp1 -> id=1 name='Krishna' age=23
emp1Dict -> {'id': 1, 'name': 'Krishna', 'age': 23}
emp1Construct -> id=1 name='Krishna' age=23

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment