Files
pydantic/docs/usage/exporting_models.md
T
Samuel Colvin 33b7d52d31 moving docs to mkdocs (#856)
* moving docs to mkdocs

* transfering readme to md and more

* fixing build

* splitting usage.md

* improving schema.md and index.md

* fix make_history.rst

* models intro

* working on data conversation and required fields

* more fixes to models.md

* list all standard types supported

* list of pydantic types

* tweaks

* update links in code

* Apply suggestions from code review

incorporate @dmontagu's suggestions.

Co-Authored-By: dmontagu <35119617+dmontagu@users.noreply.github.com>

* Apply suggestions from code review

more missed suggestions.

Co-Authored-By: dmontagu <35119617+dmontagu@users.noreply.github.com>

* Apply suggestions from code review

more corrects.

* cleanup

* Field order warning

* fix and regenerate benchmarks

* format examples better, cleanup

* improve schema mapping table

* correct highlighting file types in schema.md

* add redirects in javascript

* add logo
2019-10-07 17:19:01 +01:00

5.0 KiB

As well as accessing model attributes directly via their names (eg. model.foobar), models can be converted and exported in a number of ways:

model.dict(...)

The primary way of converting a model to a dictionary. Sub-models will be recursively converted to dictionaries.

Arguments:

  • include: fields to include in the returned dictionary, see below
  • exclude: fields to exclude from the returned dictionary, see below
  • by_alias: whether field aliases should be used as keys in the returned dictionary, default False
  • skip_defaults: whether fields which were not set when creating the model and have their default values should be excluded from the returned dictionary, default False

Example:

{!./examples/export_dict.py!}

(This script is complete, it should run "as is")

dict(model) and iteration

pydantic models can also be converted to dictionaries using dict(model), you can also iterate over a model's field using for field_name, value in model:. Here the raw field values are returned, eg. sub-models will not be converted to dictionaries.

Example:

{!./examples/export_iterate.py!}

(This script is complete, it should run "as is")

model.copy(...)

copy() allows models to be duplicated, this is particularly useful for immutable models.

Arguments:

  • include: fields to include in the returned dictionary, see below
  • exclude: fields to exclude from the returned dictionary, see below
  • update: dictionaries of values to change when creating the new model
  • deep: whether to make a deep copy of the new model, default False

Example:

{!./examples/export_copy.py!}

(This script is complete, it should run "as is")

model.json(...)

The .json() method will serialise a model to JSON. Typically, .json() in turn calls .dict() and serialises its result. (For models with a custom root type, after calling .dict(), only the value for the __root__ key is serialised.)

Serialisation can be customised on a model using the json_encoders config property, the keys should be types and the values should be functions which serialise that type, see the example below.

Arguments:

  • include: fields to include in the returned dictionary, see below
  • exclude: fields to exclude from the returned dictionary, see below
  • by_alias: whether field aliases should be used as keys in the returned dictionary, default False
  • skip_defaults: whether fields which were not set when creating the model and have their default values should be excluded from the returned dictionary, default False
  • encoder: a custom encoder function passed to the default argument of json.dumps(), defaults to a custom encoder designed to take care of all common types
  • **dumps_kwargs: any other keyword argument are passed to json.dumps(), eg. indent.

Example:

{!./examples/export_json.py!}

(This script is complete, it should run "as is")

By default timedelta's are encoded as a simple float of total seconds. The timedelta_isoformat is provided as an optional alternative which implements ISO 8601 time diff encoding.

See below for details on how to use other libraries for more performant JSON encoding and decoding

pickle.dumps(model)

Using the same plumbing as copy() pydantic models support efficient pickling and unpicking.

{!./examples/export_pickle.py!}

(This script is complete, it should run "as is")

Advanced include and exclude

The dict, json and copy methods support include and exclude arguments which can either be sets or dictionaries, allowing nested selection of which fields to export:

{!./examples/advanced_exclude1.py!}

The ellipsis (...) indicates that we want to exclude or include an entire key, just as if we included it in a set.

Of course same can be done on any depth level:

{!./examples/advanced_exclude2.py!}

Same goes for json and copy methods.

Custom JSON (de)serialisation

To improve the performance of encoding and decoding JSON, alternative JSON implementations can be used via the json_loads and json_dumps properties of Config, e.g. ujson.

{!./examples/json_ujson.py!}

(This script is complete, it should run "as is")

ujson generally cannot be used to dump JSON since it doesn't support encoding of objects like datetimes and does not accept a default fallback function argument. To do this you may use another library like orjson.

{!./examples/json_orjson.py!}

(This script is complete, it should run "as is")

Note that orjson takes care of datetime encoding natively, making it faster than json.dumps but meaning you cannot always customise encoding using Config.json_encoders.