Search code examples
pythondjangotastypie

Passing "options" to Tastypie Serializers


The documentation for Tastypie serializers and custom serializers shows options defaulting to None:

to_json(self, data, options=None):
    options = options or {}

But then downstream code doesn't seem to leverage it other than passing it to to_simple() which also does nothing with it. There's also no documentation showing how to pass options into these functions. I'd like to be able to pass options here so I can adjust how my serializers work. For example, we have content which references data in GridFS. I want to do something like:

/api/v1/foo/?format=custom&gridfs=1

And have this:

to_custom(self, data, options=None):
    options = options or {}
    if options and 'gridfs' in options:
        ...

Solution

  • I think you'll want to implement your own serializer, as explained here: http://django-tastypie.readthedocs.org/en/latest/cookbook.html#camelcase-json-serialization

    You'll also want to override the create_response function in your resource, which calls serialize: https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1174

    You can turn pass in options to serialize here, which will propagated down. For instance:

        def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
            """
            Extracts the common "which-format/serialize/return-response" cycle.
    
            Mostly a useful shortcut/hook.
            """
            desired_format = self.determine_format(request)
            serialized = self.serialize(request, data, desired_format, options=request.GET)
            return response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs
    

    For completeness, serialize is also called in error response here: https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1210