Serialize the @property methods in a Python class

You can extend Django’s serializers without /too/ much work. Here’s a custom serializer that takes a queryset and a list of attributes (fields or not), and returns JSON.

from StringIO import StringIO
from django.core.serializers.json import Serializer

class MySerializer(Serializer):
    def serialize(self, queryset, list_of_attributes, **options):
        self.options = options
        self.stream = options.get("stream", StringIO())
        self.start_serialization()
        for obj in queryset:
            self.start_object(obj)
            for field in list_of_attributes:
                self.handle_field(obj, field)
            self.end_object(obj)
        self.end_serialization()
        return self.getvalue()

    def handle_field(self, obj, field):
        self._current[field] = getattr(obj, field)

Usage:

>>> MySerializer().serialize(MyModel.objects.all(), ["field1", "property2", ...])

Of course, this is probably more work than just writing your own simpler JSON serializer, but maybe not more work than your own XML serializer (you’d have to redefine “handle_field” to match the XML case in addition to changing the base class to do that).

Leave a Comment