Hi all,
Over the coding sprints at
djangocon.eu I started working on a proposal for customizable serialization. [1]
I've talked over the API and implementation with Russ, and I think we're broadly happy with it all,
so I'd like to open it up to wider discussion.
What I have right now looks something like this:
1) Serialization is a two stage process - firstly serializing into native datatypes, then rendering into json/xml/whatever.
2) Serialization behavior is specified by inheriting from a Serializer class and setting various attributes such as 'fields', 'depth' etc... on an inner 'Meta' class.
3) Serialization of a given field on a model can be overridden by specifying a method on the Serialization class.
4) Behavior can also be refined by overriding various public methods on the Serializer class, if required.
5) Multiple Serialization classes can be composed together, to provide for more complex behavior.
Here's an example of the proposed API, that replicates the existing json serialization behavior, without any of the implicit assumptions about serialization structure that are currently made:
class PKOnlySerializer(Serializer):
"""
Serializes models into their pk representation.
"""
def serialize_model(self, instance):
class FieldsSerializer(Serializer):
"""
Serializes only the fields on a model.
"""
class Meta:
exclude = ('id', 'pk')
related_serializer = PKOnlySerializer
class DjangoSerializer(Serializer):
"""
Serializes into the existing django style.
"""
class Meta:
fields = ('pk', 'model', 'fields')
def model(self, instance):
return unicode(instance._meta)
def fields(self, instance):
return FieldsSerializer().serialize(instance)
Which can be used like this:
data = DjangoSerializer().serialize(queryset)
ret = json.dumps(data, cls=DateTimeAwareJSONEncoder, indent=4, sort_keys=False)
The code as it stands is available on github [2].
You'll want to look at impl.py [3] for the implementation and views.py [4] for example API usage.
The serializer currently supports depth-limited and recursion-limited output, and I'm right now I'm looking to work on finalizing the xml related issues,
adding some slightly more concise ways of being able to describe nested models [Russ: I think this'll be closer to what you were looking for], and then
trying to refactor Django to use the new serialization code, and see what test breakage I come up against.
Would def welcome any constructive criticism of the API or implementation.
Also if anyone wants to help in contributing in order to get this (long outstanding) feature into Django, that would be very much appreciated.
(I suspect there might be quite a lot to do once I look at merging into Django!)
It's not totally impossible that we might be able to get this feature in for 1.4, which'd be pretty cool,
and there's also a bunch of serialization related tickets that we might be able to close off in the process. [5]
Feedback?
t.