File: overriding_attribute_access.rst

package info (click to toggle)
python-marshmallow 3.26.1-0.4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,296 kB
  • sloc: python: 11,513; makefile: 11; sh: 8
file content (17 lines) | stat: -rw-r--r-- 742 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Overriding how attributes are accessed
======================================

By default, marshmallow uses `utils.get_value <marshmallow.utils.get_value>` to pull attributes from various types of objects for serialization. This will work for *most* use cases.

However, if you want to specify how values are accessed from an object, you can override the :meth:`get_attribute <marshmallow.Schema.get_attribute>` method.

.. code-block:: python

    class UserDictSchema(Schema):
        name = fields.Str()
        email = fields.Email()

        # If we know we're only serializing dictionaries, we can
        # use dict.get for all input objects
        def get_attribute(self, obj, key, default):
            return obj.get(key, default)