Saturday, 11 September 2021

Pydantic: how to specify nested properties to the arguments exclude, include and update

Arguments to the properties include, exclude can be specified using either set or dictionary. You can use dictionary to specify nested properties. Let’s see it with an example.

 

Example

emp1Json = emp1.json(exclude = {'address' : {'street', 'country'}})
emp2Json = emp1.json(exclude = {'address' : {'street', 'country'}, 'age': ...})

 

'...' indicates that we want to exclude or include an entire key.

 

specify_nested_properties.py

 

from pydantic import BaseModel, ValidationError

class Address(BaseModel):
    street: str
    city: str
    country: str

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

emp1 = Employee(id = 1, name = 'Ptr', age = 23, address = Address(street = 'Chowdeswari', city = "Bangalore", country = 'India'))

emp1Json = emp1.json(exclude = {'address' : {'street', 'country'}})
emp2Json = emp1.json(exclude = {'address' : {'street', 'country'}, 'age': ...})

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

 

Output

emp1Json -> {"id": 1, "name": "Ptr", "age": 23, "address": {"city": "Bangalore"}}
emp2Json -> {"id": 1, "name": "Ptr", "address": {"city": "Bangalore"}}

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment