Sunday, 12 September 2021

Pydantic: Exclude a field from all the elements of a set, list or tuple

Using the dictionary key '__all__', we can exclude a field from every member of a list or tuple.

 

Example

emp1Json = emp1.json(exclude={'addresses': {'__all__': {'city'}}})

 

exclude_a_field_from_list.py

from pydantic import BaseModel, ValidationError
from typing import List

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

class Employee(BaseModel):
    id: int
    name: str
    age: int
    addresses: List[Address]

emp1 = Employee(id = 1, name = 'Ptr', age = 23, addresses = 
    [
    Address(street = 'Chowdeswari', city = "Bangalore", country = 'India'),
    Address(street = 'Panchayat street', city = "Amaravathi", country = 'India'),
    ]
)

emp1Json = emp1.json(exclude={'addresses': {'__all__': {'city'}}})
print(emp1Json)

 

Output

{"id": 1, "name": "Ptr", "age": 23, "addresses": [{"street": "Chowdeswari", "country": "India"}, {"street": "Panchayat street", "country": "India"}]}

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment