| 1 |
Accessing the data |
| 2 |
------------------ |
| 3 |
|
| 4 |
Sometimes, it doesn't make sense for data to be immediately parsed into an instance of the target class. We just saw an |
| 5 |
example of this in the previous section, :ref:`read-only-fields`. When required fields are excluded from, or do not |
| 6 |
exist in the client submitted data we will get an error upon instantiation of the class. |
| 7 |
|
| 8 |
The solution to this is the :class:`DTOData <litestar.dto.data_structures.DTOData>` type. |
| 9 |
|
| 10 |
.. literalinclude:: /examples/data_transfer_objects/factory/tutorial/dto_data.py |
| 11 |
:language: python |
| 12 |
:linenos: |
| 13 |
:emphasize-lines: 6,26,28 |
| 14 |
|
| 15 |
The :class:`DTOData <litestar.dto.data_structures.DTOData>` type is a container for data that can be used to create instances, |
| 16 |
and access the underlying parsed and validated data. In our latest adjustments, we import that from |
| 17 |
``litestar.dto.factory``. |
| 18 |
|
| 19 |
The handler function's data parameter type is changed to ``DTOData[Person]`` instead of ``Person``, and accordingly, the |
| 20 |
value injected to represent the inbound client data will be an instance of |
| 21 |
:class:`DTOData <litestar.dto.data_structures.DTOData>`. |
| 22 |
|
| 23 |
In the handler, we produce a value for the ``id`` field, and create an instance of ``Person`` using the |
| 24 |
:meth:`create_instance <litestar.dto.data_structures.DTOData.create_instance>` method of the ``DTOData`` instance. |
| 25 |
|
| 26 |
And our app is back to a working state: |
| 27 |
|
| 28 |
.. image:: images/dto_data.png |
| 29 |
:align: center |
| 30 |
|
| 31 |
.. tip:: |
| 32 |
To provide values for nested attributes you can use the "double-underscore" syntax as a keyword argument to the |
| 33 |
:meth:`create_instance() <litestar.dto.data_structures.DTOData.create_instance>` method. For example, ``address__id=1`` will |
| 34 |
set the ``id`` attribute of the ``address`` attribute of the created instance. |
| 35 |
|
| 36 |
See :ref:`dto-create-instance-nested-data` for more information. |
| 37 |
|
| 38 |
The :class:`DTOData <litestar.dto.data_structures.DTOData>` type has some other useful methods, and we'll take a look at those |
| 39 |
in the next section: :ref:`updating`. |