pydantic models

Model properties

pydantic models have the following methods and attributes:

dict()

Returns a dictionary of the model's attributes and their values;

returns a dictionary of the model's fields and values; cf. exporting models

In the example below I will demonstrate .dict() and also compare it with .json()

json()

Returns a dictionary of the model's attributes and their values in JSON representation;

returns a JSON string representation dict(); cf. exporting models

An example for .dict() and .json()

from pydantic import BaseModel class User(BaseModel): id: int name = 'Jane Doe' user = User(id='123') print(user.dict()) print(user.json())

{'id': 123, 'name': 'Jane Doe'}

{"id": 123, "name": "Jane Doe"}

In this example the difference between .json() and .dict() is not too obvious - only the quotes changed, that is all

Let us create a slightly more complex object. Let us import Tuple to create tuples

from pydantic import BaseModel from typing import Tuple class User(BaseModel): id: int sites = Tuple[str,...] user = User(id='123',sites='heihei.ru','eth1.ru') print(user.dict()) print(user.json())

{'id': 123, 'sites': ('heihei.ru', 'eth1.ru')}

{"id": 123, "sites": ["heihei.ru", "eth1.ru"]}

copy()

Returns a copy (by default - shallow) of the model.

returns a copy (by default, shallow copy) of the model; cf. exporting models

Note that a shallow (not deep) copy will change if the original changes.

Consider the example:

from pydantic import BaseModel class User(BaseModel): id: int name = 'Vladimir Vladimirovich' user = User(id='123') abuser = user.copy() print(user.json()) print(abuser.json()) user.id = 456 print(user.json()) print(abuser.json())

{"id": 123, "name": "Vladimir Vladimirovich"}
{"id": 123, "name": "Vladimir Vladimirovich"}
{"id": 456, "name": "Vladimir Vladimirovich"}
{"id": 456, "name": "Vladimir Vladimirovich"}

parse_obj()

a utility for loading any object into a model with error handling if the object is not a dictionary; cf. helper functions

parse_raw()

a utility for loading strings of numerous formats; cf. helper functions

parse_file()

like parse_raw() but for file paths; cf. helper function

from_orm()

loads data into a model from an arbitrary class; cf. ORM mode

schema()

returns a dictionary representing the model as JSON Schema; cf. schema

schema_json()

returns a JSON string representation of schema(); cf. schema

construct()

a class method for creating models without running validation; cf. Creating models without validation

__fields_set__

Set of names of fields which were set when the model instance was initialised

__fields__

a dictionary of the model's fields

__config__

the configuration class for the model, cf. model config

Article author: Andrei Olegovich