Skip to content

Instantly share code, notes, and snippets.

@grapo
grapo / gist:3085250
Created July 10, 2012 18:14
Django serialization

##Django declarative (de)serializers

Serializer is a class that can serialize and deserialize objects like Django models from and to serialization format (json, xml, pyyaml). It is composed from two classes: NativeSerializer and FormatSerializer. NativeSerializer is for serializing and deserializing objects to/from python native datatypes:

  • Iterables are serialized to list generators
  • Objects are serialized to dicts FormatSerializer is for serializing and deserializing python native datatypes to/from serialization format (json, xml, pyyaml).

If some format is defined then user can serialize user_data to this format with 'serializers.serialize' function:

@grapo
grapo / gist:2597306
Created May 4, 2012 19:53
Revised serialization

It's my revised proposal on customizable serialization. Based on Tom Christie's django-serializers https://github.com/tomchristie/django-serializers I updated some of my ideas.

My idea of serialization is to have a black box serializer where you put:

  • objects - single object, list, queryset, ?dict?
  • Serializer class
  • format (far now I consider only xml, json and yaml like in present Django solution)

This black box serializer is an chain of two generators. First generates python native datatype and second produces from it serialized string stream. Splitting serialization to two phases is the best approach :) It should be easier then to add other unsupported formats. There is some issues on this stage:

  • what with objects contains iterable of other objects (e.g. reverse related, m2m) - it should be expand to list or return as generator? I believe second option is better. In rest of my proposal assume that generators which returns python native datatypes are also python natives.
@grapo
grapo / gist:2319638
Created April 6, 2012 13:09
Customizable serialization

Introduction:

If we want to serialize objects we must consider two questions:

  1. What to serialize? Which fields of objects, how deep to serialize related objects.
  2. How output should looks like? Which format (xml, json, yaml), fields renaming, some format specific options (like attributes in xml - nothing similar in json), order of fields, some fields in other place in structure tree than others.

This questions lead as to two phases of serialization:

  1. First phase "dehydration": Change class instances (generally Python class, particular Django Model class) to dictionary contains data(python native types) of all interesting us fields. In this stage we are not interested in specific format.