Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
126 lines (82 sloc) 2.89 KB

Welcome to Serializer documentation!

Serializer provides Easy object serialization. Mimics RoR ActiveRecord serializer.


  1. Make your class inherit Serializable mixin.
  2. Define attributes() method and make it return a list of property names


from serializer import Serializable

class User(Serializable):
    first_name = 'John'
    last_name = 'Matrix'
    email = ''
    protected_property = 'this value is not included in json'

    def attributes(self):
        return ['first_name', 'last_name', 'email']

user = User()
# "{'first_name': 'John', 'last_name': 'Matrix'}"

# {'first_name': 'John', 'last_name': 'Matrix'}

How to handle relations

Serializer supports serializing of deep object structures. Let's say we have two classes Event and Location and we want to jsonify an event along with its location.

class Location(Serializable):
    name = 'Some Location'

    def attributes(self):
        return ['name']

class Event(Serializable):
    name = 'Some Event'
    location = Location()

    def attributes(self):
        return ['name', 'location']

event = Event()
# "{'name': 'Some Event', 'location': {'name': 'Some Location'}}"

Using exclude, include and only

You can fine-grain what gets included in json format by using exclude, include and only parameters.

User.as_json(only=['name', 'email'])  # include only name and email

# include all the fields defined in attributes as well as age

# include all the field defined in attributes but exclude 'email'

Using attribute sets

Many times you may have situations where having one default attribute list is not enough. For example you may have multiple views that return user details and many views that return user with only its basic info.

class User(Serializable):
    first_name = 'John'
    last_name = 'Matrix'
    email = ''
    age = 33
    is_active = True

    def attributes(self):
        return ['first_name', 'last_name', 'email']

    def attribute_sets(self):
        return {'details': ['age', 'is_active']}

user = User()
        'first_name': 'John',
        'last_name': 'Matrix',
        'email': '',
        'age': 33,
        'is_active': True

API Documentation

.. module:: serializer
.. autoclass:: Serializable
.. autofunction:: register_dumper