| 1 |
.. _read-only-fields: |
| 2 |
|
| 3 |
Read only fields |
| 4 |
---------------- |
| 5 |
|
| 6 |
Sometimes, fields should never be able to be specified by the client. For example, upon creation of a new resource |
| 7 |
instance, the ``id`` field of a model should be generated by the server and not specified by the client. |
| 8 |
|
| 9 |
.. literalinclude:: /examples/data_transfer_objects/factory/tutorial/read_only_fields_error.py |
| 10 |
:language: python |
| 11 |
:linenos: |
| 12 |
:emphasize-lines: 14 |
| 13 |
|
| 14 |
In this adjustment, we add an ``id`` field to the ``Person`` model. We also create a new class, ``WriteDTO`` that is |
| 15 |
instructed to ignore the ``id`` attribute. |
| 16 |
|
| 17 |
The ``WriteDTO`` class is assigned to the handler via the ``dto`` kwarg (``dto=WriteDTO``) meaning that the ``id`` field |
| 18 |
will be ignored from any data received from the client when creating a new ``Person`` instance. |
| 19 |
|
| 20 |
When we try to create a new ``Person`` instance with an ``id`` field specified, we get an error: |
| 21 |
|
| 22 |
.. image:: images/read_only_fields_error.png |
| 23 |
:align: center |
| 24 |
|
| 25 |
What's happening? The DTO is trying to construct an instance of the ``Person`` model but we have excluded the ``id`` |
| 26 |
field from the accepted client data. The ``id`` field is required by the ``Person`` model, so the model constructor |
| 27 |
raises an error. |
| 28 |
|
| 29 |
There is more than one way to address this issue, for example we could assign a default value to the ``id`` field and |
| 30 |
overwrite the default in the handler, or we could create an entirely separate model that has no ``id`` field, and |
| 31 |
transfer the data from that to the ``Person`` model in the handler. However, Litestar has a built-in solution for this: |
| 32 |
:class:`DTOData <litestar.dto.data_structures.DTOData>`. |