传递"选项"到Tastypie Serializers

时间:2014-03-27 18:30:10

标签: python django tastypie

Tastypie序列化程序和自定义序列化程序的文档显示options默认为None

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

但是,下游代码似乎并没有利用它而不是将其传递给to_simple(),而/api/v1/foo/?format=custom&gridfs=1 也没有做任何事情。还没有文档显示如何将选项传递到这些函数中。我希望能够在此处传递选项,以便我可以调整序列化程序的工作方式。例如,我们有内容引用GridFS中的数据。我想做点什么:

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

并且有这个:

{{1}}

1 个答案:

答案 0 :(得分:2)

我认为你想要实现自己的序列化程序,如下所述: http://django-tastypie.readthedocs.org/en/latest/cookbook.html#camelcase-json-serialization

您还要覆盖资源中的create_response功能,该功能会调用serializehttps://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1174

您可以将options中的传递转到此处序列化,这将传播下来。例如:

    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

为了完整性,此处还会在错误响应中调用serializehttps://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1210