views:

37

answers:

2

Hi !

I am currently writing an API for a django project, and using django-piston for this. However, I need to customize the way certain base types are serialized.

More precisely, my models are subclassed from a special Model class, which inherits from django.db.models.base.ModelBase, but cannot be serialized as regular django models ... Therefore, I would like to override the serializer for all subclasses of this special Model class.

I don't know piston well ... I've looked at the code, and the mapping type->serializer (for base types) seems to be hard-coded.

Does anybody know if there is a standard way to override it ???

+1  A: 

You can do the serialization yourself. The handlers only expect and return a python dictionary. For this though, you can't just plug it into a model. Create your own resource handler for your base type, which is capable of building your Model from a dict.

class ModelHandler(HandlerBase):
    allowed_methods = ('Get',)

    def read(self, request, id=None):
        if id is not None:
            m = Model.objects.get(id=id)

        ret = {}
        ret['field'] = m.field

        return ret
Josh Smeaton
Yeah... I thought about this. But basically, that means I have to re-write the serialization myself !
sebpiq
@seb The classes you use can't be serialized conventially, by your own words. Therefore you have to do the serialization yourself. If you've got many different classes that need to be serialized the same way, have a BaseModelHandler that all your specific handlers derive from. Then you've captured the serialization in one place. You have to do it yourself, unless the django-ldapdb people have a serializer.
Josh Smeaton
A: 

Ok ... I couldn't have it working, so I took some code that I had written myself some time ago, made it cleaner, it ended-up in a full Python serialization framework SpitEat. I have begun writing some documentation, but it's a work in progress.

I have given-up using piston, since it is not the first time it disappoints me by its lack of flexibility on (de)serialization operations.

SpitEat aims to be fully customizable, (by seeing serialization from a more abstract point of view than just "django objects") and provides serializers for Django, tested, but not so well documented yet, and with features that are still missing (again it is a work in progress).

sebpiq