pydantic models

Model properties

У моделей pydantic есть следующие методы и аттрибуты:

dict()

Возвращает словарь из аттрибутов модели и их значений;

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

В примере ниже я продемонстрирую .dict() а также сравню его с .json()

json()

Возвращает словарь из аттрибутов модели и их значений в представлении JSON;

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

Пример для .dict() и .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"}

На этом примере разница между .json() и .dict() не слишком очевидна - поменялись кавычки и всё

Создадим чуть более сложный объект. Импортируем Tuple для создания кортежей

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 copy) of the model; cf. exporting models

Обратите внимание, что поверхносная (неглубокая) копия будет изменяться если изменился ориганал.

Рассмотрите пример:

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

Related articles
Python
Интерактивный режим
str: строки
\: перенос строки
Списки []
if, elif, else
Циклы
Методы
Функции
*args **kwargs
enum
Опеределить тип переменной Python
Тестирование с помощью Python
Работа с REST API на Python
Файлы: записать, прочитать, дописать, контекстный менеджер…
Скачать файл по сети
SQLite3: работа с БД
datetime: Date and Time в Python
json.dumps
Selenium + Python
Сложности при работе с Python
DJANGO
Flask
Скрипт для ZPL принтера
socket :Python Sockets
Виртуальное окружение
subprocess: выполнение bash команд из Python
multiprocessing: несколько процессов одновременно
psutil: cистемные ресурсы
sys.argv: аргументы командной строки
PyCharm: IDE
pydantic: валидация данных
paramiko: SSH из Python
enumerate

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: