来自canonical_resource_for('object')的Tastypie构建数据包

时间:2012-08-31 08:32:51

标签: python django tastypie

我正在尝试编写一个Django TemplateView,它根据tastypie的规范资源返回包含JSON的上下文参数'data':

资源

class FooResource(ModelResource):
    bars = fields.ToManyField('app.api.v1.resources.BarResource', 'bars', null=True, full=True)

    class Meta:
        queryset = Foo.objects.all()
        resource_name = 'foo'
        # ...

模型

class FooDetailView(TemplateView):
    template_name = 'app/foo_detail.html'

    def get_detail(self, slug):
        foo_resource = v1_api.canonical_resource_for('foo')

        try:
            foo = foo_resource.cached_obj_get(slug=slug)
        except Foo.DoesNotExist:
            raise Http404

        bundle = foo_resource.full_dehydrate(foo_resource.build_bundle(obj=foo))
        return bundle.data

    def get_context_data(self, **kwargs):
        base = super(FooDetailView, self).get_context_data(**kwargs)
        base['data'] = self.get_detail(base['params']['slug'])
        return base

这样可行,但是Foo和Bar之间的反向关系似乎没有被手动过程序列化。 TemplateView将这些作为字符串返回,这是响应:

{
    'title': u'I am Foo.title',
    'bars': [<Bundle for obj: '1' and with data: '{'title': u'I am Bar.title'}']
}

那么,问题是,在构建捆绑包时如何迭代反向关系?

1 个答案:

答案 0 :(得分:0)

答案是在脱水后通过resource.serializer运行bundle

def get_detail(self, slug):
    qr = v1_api.canonical_resource_for('question')
    try:
        question = qr.cached_obj_get(slug=slug)
    except Question.DoesNotExist:
        raise Http404

    bundle = qr.full_dehydrate(qr.build_bundle(obj=question))

    # create response
    desired_format = qr.determine_format(self.request)
    serialized = qr.serialize(self.request, bundle, desired_format)
    return serialized