简体   繁体   English

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

[英]Tastypie building data bundle from canonical_resource_for('object')

I am trying to write a Django TemplateView that returns a context parameter 'data' containing JSON based on tastypie's canonical resource: 我正在尝试编写一个Django TemplateView,该模板返回一个基于asteapie的规范资源包含JSON的上下文参数“数据”:

resources 资源

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'
        # ...

models 楷模

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

This works, however the reverse relationship between Foo and Bar doesn't seem to get serialized by the manual process. 这行得通,但是Foo和Bar之间的反向关系似乎没有通过手动过程序列化。 The TemplateView returns these as strings, here's the response: TemplateView将它们作为字符串返回,这是响应:

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

So, question, how do I iterate over the reverse relationships when building the bundle? 因此,问题是,在构建捆绑包时如何迭代反向关系?

The answer was to run bundle through the resource.serializer after dehydrating 答案是在脱水后通过resource.serializer运行捆绑软件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM