mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
f55515820a
* renaming .json -> .model_dump_json * renaming .dict -> .model_dump * renaming .__fields__ -> .model_fields * renaming .schema -> .model_json_schema * renaming .construct -> .model_construct * renaming .parse_obj -> .model_validate * make linters happy * add changes md-file Co-authored-by: Samuel Colvin <s@muelcolvin.com>
74 lines
1.5 KiB
Python
74 lines
1.5 KiB
Python
import datetime
|
|
from typing import List
|
|
|
|
from pydantic import BaseModel, SecretStr
|
|
|
|
|
|
class Country(BaseModel):
|
|
name: str
|
|
phone_code: int
|
|
|
|
|
|
class Address(BaseModel):
|
|
post_code: int
|
|
country: Country
|
|
|
|
|
|
class CardDetails(BaseModel):
|
|
number: SecretStr
|
|
expires: datetime.date
|
|
|
|
|
|
class Hobby(BaseModel):
|
|
name: str
|
|
info: str
|
|
|
|
|
|
class User(BaseModel):
|
|
first_name: str
|
|
second_name: str
|
|
address: Address
|
|
card_details: CardDetails
|
|
hobbies: List[Hobby]
|
|
|
|
|
|
user = User(
|
|
first_name='John',
|
|
second_name='Doe',
|
|
address=Address(
|
|
post_code=123456,
|
|
country=Country(
|
|
name='USA',
|
|
phone_code=1
|
|
)
|
|
),
|
|
card_details=CardDetails(
|
|
number=4212934504460000,
|
|
expires=datetime.date(2020, 5, 1)
|
|
),
|
|
hobbies=[
|
|
Hobby(name='Programming', info='Writing code and stuff'),
|
|
Hobby(name='Gaming', info='Hell Yeah!!!'),
|
|
],
|
|
)
|
|
|
|
exclude_keys = {
|
|
'second_name': True,
|
|
'address': {'post_code': True, 'country': {'phone_code'}},
|
|
'card_details': True,
|
|
# You can exclude fields from specific members of a tuple/list by index:
|
|
'hobbies': {-1: {'info'}},
|
|
}
|
|
|
|
include_keys = {
|
|
'first_name': True,
|
|
'address': {'country': {'name'}},
|
|
'hobbies': {0: True, -1: {'name'}},
|
|
}
|
|
|
|
# would be the same as user.model_dump(exclude=exclude_keys) in this case:
|
|
print(user.model_dump(include=include_keys))
|
|
|
|
# To exclude a field from all members of a nested list or tuple, use "__all__":
|
|
print(user.model_dump(exclude={'hobbies': {'__all__': {'info'}}}))
|