我正在尝试编写一个 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'}']
}
那么,问题是,在构建捆绑包时如何迭代反向关系?