0

我正在尝试编写一个 Django TemplateView,它返回一个上下文参数“数据”,其中包含基于美味派规范资源的 JSON:

资源

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'}']
}

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

4

1 回答 1

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
于 2012-08-31T13:53:29.733 回答