bruth/django-preserialize

Add ability to define object hooks for customizing output during serialization

bruth opened this issue · 1 comments

Often times there are slight representation tweaks that are desirable or the ability to augment a value to the resource. For model objects this can typically be done using model properties or methods. Some things (like building the resource URL) is not appropriate to add to the model in my opinion. Other must be simple value/type formatting.

A new option called hooks could be defined which is a dict where the keys are the output fields and the values are functions or a static value (good for placeholders or filling in _gaps):

>>> template = {
...         'fields': [':pk', 'first_name', 'last_name', 'permissions'],
...         'hooks': {
...             'permissions': lambda x: str(x),
...         }
...     },
... }

>>> serialize(user, **template)
{
    'id': 1,
    'first_name': 'John',
    'last_name': 'Doe',
    'permissions': [
         'auth | group | Can add group',
         'auth | group | Can change group',
         'auth | group | Can delete group',
         'auth | permission | Can add permission',
         'auth | permission | Can change permission',
         # ...
    ],
}

Implemented using the prehook and posthook options.