Debian Codegraph @

docs/tutorials/dto-tutorial/05-renaming-fields.rst

raw
1 Renaming fields
2 ---------------
3
4 The name of a field that is used for serialization can be changed by either explicitly declaring the new name or by
5 declaring a renaming strategy.
6
7 Explicitly renaming fields
8 ==========================
9
10 We can rename fields explicitly using the :attr:`rename_fields <litestar.dto.config.DTOConfig.rename_fields>`
11 attribute. This attribute is a dictionary that maps the original field name to the new field name.
12
13 In this example, we rename the ``address`` field to ``location``:
14
15 .. literalinclude:: /examples/data_transfer_objects/factory/tutorial/explicit_field_renaming.py
16 :language: python
17 :linenos:
18 :emphasize-lines: 28
19
20 Notice how the ``address`` field is renamed to ``location``.
21
22 .. image:: images/explicit_field_renaming.png
23 :align: center
24
25 Field renaming strategies
26 =========================
27
28 Instead of explicitly renaming fields, we can also use a field renaming strategy.
29
30 The field renaming strategy is specified using the
31 :attr:`rename_strategy <litestar.dto.config.DTOConfig.rename_strategy>` config.
32
33 Litestar supports the following strategies:
34
35 - ``lower``: Converts the field name to lowercase
36 - ``upper``: Converts the field name to uppercase
37 - ``camel``: Converts the field name to camel case
38 - ``pascal``: Converts the field name to pascal case
39
40 .. note::
41
42 You can also define your own strategies by passing a callable that receives the field name, and returns the new
43 field name to the ``rename_strategy`` config.
44
45 Let's modify our example to use the ``upper`` strategy:
46
47 .. literalinclude:: /examples/data_transfer_objects/factory/tutorial/field_renaming_strategy.py
48 :language: python
49 :linenos:
50 :emphasize-lines: 28
51
52 And the result:
53
54 .. image:: images/field_renaming_strategy.png
55 :align: center