| 1 |
.. _updating: |
| 2 |
|
| 3 |
Updating instances |
| 4 |
------------------ |
| 5 |
|
| 6 |
In this section we'll see how to update existing instances using :class:`DTOData <litestar.dto.data_structures.DTOData>`. |
| 7 |
|
| 8 |
PUT handlers |
| 9 |
============ |
| 10 |
|
| 11 |
`PUT <https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT>`_ requests are characterized by requiring the |
| 12 |
full data model to be submitted for update. |
| 13 |
|
| 14 |
.. literalinclude:: /examples/data_transfer_objects/factory/tutorial/put_handlers.py |
| 15 |
:language: python |
| 16 |
:linenos: |
| 17 |
:emphasize-lines: 25,28,29 |
| 18 |
|
| 19 |
This script defines a ``PUT`` handler with path ``/person/{person_id:int}`` that includes a route parameter, |
| 20 |
``person_id`` to specify which person should be updated. |
| 21 |
|
| 22 |
In the handler, we create an instance of ``Person``, simulating a database lookup, and then pass it to the |
| 23 |
:meth:`DTOData.update_instance() <litestar.dto.data_structures.DTOData.update_instance>` method, which returns the same instance |
| 24 |
after modifying it with the submitted data. |
| 25 |
|
| 26 |
.. image:: images/put_handlers.png |
| 27 |
:align: center |
| 28 |
|
| 29 |
PATCH handlers |
| 30 |
============== |
| 31 |
|
| 32 |
`PATCH <https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH>`_ requests are characterized by allowing any |
| 33 |
subset of the properties of the data model to be submitted for update. This is in contrast to |
| 34 |
`PUT <https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT>`_ requests, which require the entire data model |
| 35 |
to be submitted. |
| 36 |
|
| 37 |
.. literalinclude:: /examples/data_transfer_objects/factory/tutorial/patch_handlers.py |
| 38 |
:language: python |
| 39 |
:linenos: |
| 40 |
:emphasize-lines: 21,22,25 |
| 41 |
|
| 42 |
In this latest update, the handler has been changed to a :class:`@patch() <litestar.handlers.patch>` |
| 43 |
handler. |
| 44 |
|
| 45 |
This script introduces the ``PatchDTO`` class that has a similar configuration to ``WriteDTO``, with the ``id`` field |
| 46 |
excluded, but it also sets :attr:`partial=True <litestar.dto.config.DTOConfig.partial>`. This setting allows for |
| 47 |
partial updates of the resource. |
| 48 |
|
| 49 |
And here's a demonstration of use: |
| 50 |
|
| 51 |
.. image:: images/patch_handlers.png |
| 52 |
:align: center |