| 1 |
Excluding from collections of nested models |
| 2 |
------------------------------------------- |
| 3 |
|
| 4 |
In Python, generic types can accept one or more type parameters (types that are enclosed in square brackets). This |
| 5 |
pattern is often seen when representing a collection of some type, such as ``List[Person]``, where ``List`` is a |
| 6 |
generic container type, and ``Person`` specializes the contents of the collection to contain only instances of the |
| 7 |
``Person`` class. |
| 8 |
|
| 9 |
Given a generic type, with an arbitrary number of type parameters (e.g., ``GenericType[Type0, Type1, ..., TypeN]``), |
| 10 |
we use the index of the type parameter to indicate which type the exclusion should refer to. For example, ``a.0.b``, |
| 11 |
excludes the ``b`` field from the first type parameter of ``a``, ``a.1.b`` excludes the ``b`` field from the second type |
| 12 |
parameter of ``a``, and so on. |
| 13 |
|
| 14 |
To demonstrate, lets add a self-referencing ``children`` relationship to our ``Person`` model: |
| 15 |
|
| 16 |
.. literalinclude:: /examples/data_transfer_objects/factory/tutorial/nested_collection_exclude.py |
| 17 |
:language: python |
| 18 |
:linenos: |
| 19 |
:emphasize-lines: 22,26,34,35,41 |
| 20 |
|
| 21 |
Now, a ``Person`` can have one or many ``children``, and each ``child`` can have one or many ``children``, and so on. |
| 22 |
|
| 23 |
We have explicitly excluded the ``email`` and ``address`` fields of all represented ``children`` |
| 24 |
(``"children.0.email", "children.0.address"``). |
| 25 |
|
| 26 |
In our handler we add ``children`` to the ``Person``, and each child has no ``children`` of their own. |
| 27 |
|
| 28 |
Here's the output: |
| 29 |
|
| 30 |
.. image:: images/nested_collection_exclude.png |
| 31 |
:align: center |
| 32 |
|
| 33 |
Fantastic! Our ``children`` are now represented in the output, and their emails and addresses are excluded. However, |
| 34 |
astute readers may have noticed that we didn't exclude the ``children`` field of ``Person.children`` |
| 35 |
(e.g., ``children.0.children``), yet that field is not represented in the output. To understand why, we'll next look at |
| 36 |
the :attr:`max_nested_depth <litestar.dto.config.DTOConfig.max_nested_depth>` configuration option. |