如何在POST请求中返回数据(django / tastypie)

时间:2014-04-16 03:07:40

标签: django tastypie

如何在POST请求的响应中自定义和放置数据? 起初我以为我应该将代码放在obj_create中,但看起来create_response是我放置代码的地方。

我的资源如下:

class TestResource(ModelResource):
    class Meta:
        queryset = Test.objects.all()
        always_return_data = True
        authentication = Authentication()
        authorization = Authorization()

    def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
        super(TestResource, self).create_response(request, data, response_class, **response_kwargs)

但是我收到HTTP/1.0 204 NO CONTENT错误;当我删除create_response函数时,它正常工作。不应该超级调用我所覆盖的功能没有效果吗?

1 个答案:

答案 0 :(得分:3)

您必须返回响应。

def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
    return super(TestResource, self).create_response(request, data, response_class, **response_kwargs) 

但我会使用dehydrate方法:

class TestResource(ModelResource):
    class Meta:
        queryset = Test.objects.all()
        always_return_data = True
        authentication = Authentication()
        authorization = Authorization()

    def dehydrate(self, bundle):
        if bundle.request.method == 'POST':
            bundle.data['my_custom_data'] = 'my_data'

        return bundle