获取tastypie中的对象列表(在另一个视图中)

时间:2012-06-01 01:11:15

标签: django tastypie

我正试图在另一个视图中使用tastypie响应。我见过the recipe in the cookbook。问题是,我想获得列表视图。就我而言,/api/v1/source/。这是我到目前为止所得到的:

sr = SourceResource()
objs = sr.get_object_list(request) # two objects returned
bun = sr.build_bundle(data=objs, request=request)

jsondata = sr.serialize(None, sr.full_dehydrate(bun), 'application/json')

当然这一切都崩溃了。 bun.data没有所需的特征(单个对象)。那么,有没有人成功完成这项工作?怎么做?

2 个答案:

答案 0 :(得分:5)

这就是我想出的。我并不特别喜欢请求和QueryDict都被复制,但除了复制the tastypie code的大部分内容之外,我现在无法想到任何其他内容。

from copy import copy

from django.views.generic import TemplateView

from incremental.sources.resources import SourceResource
resource = SourceResource()

class AppView(TemplateView):
    'Base view for the Source parts of the app'
    template_name = 'sources/base.html'

    def get_context_data(self, **data):
        'get context data'
        tmp_r = copy(self.request)
        tmp_r.GET = tmp_r.GET.copy()
        tmp_r.GET['format'] = 'json'

        data.update({
            'seed': resource.get_list(tmp_r).content
        })
        return data

答案 1 :(得分:3)

为了避免请求复制内容,您可以将json设置为默认格式,例如在您的资源中,您可以重载以下方法:

SourceResource(Resource):
  def determine_format(self, request):
    return "application/json"