如何在tastypie中只返回一个字段?

时间:2013-10-07 12:50:22

标签: django json tastypie

假设我有一个类似下面的资源..

class PostResource(ModelResource):

    children = fields.ToManyField('MyApp.api.resources.PostResource',
                 attribute='comments', full=True, null=True)

基本上,我只想返回这个子字段并将其展平。

看起来像是 [ {child-1-data}, {child-2-data} ]
而不是 { children: [ {child-1-data}, {child2-data} ] }

我该怎么做?

另外,如果我想要一个相同模型类的不同表示,我应该创建一个新的资源类,如下所示?

class PostNormalResource(ModelResource):
      class Meta:
          queryset= models.Post.objects.all()
          fields = ['text', 'author']

2 个答案:

答案 0 :(得分:0)

不是你正在寻找的答案,而是我在挖掘时所做的一些发现。

通常您会修改dehydrate中的捆绑数据。请参阅tastypie cookbook

def dehydrate(self, bundle):
    bundle.data['custom field'] = "This is some additional text on the resource"
    return bundle

这表示您可以按照以下方式操纵PostResource的捆绑数据:

def dehydrate(self, bundle):
    # Replace all data with a list of children
    bundle.data = bundle.data['children']
    return bundle

然而,这将是错误AttributeError: 'list' object has no attribute 'items',因为tastypie序列化程序正在寻找序列化字典而不是列表。

# "site-packages/tastypie/serializers.py", line 239
return dict((key, self.to_simple(val, options)) for (key, val) in data.data.items())

# .items() being for dicts

因此,这表明您需要查看不同的序列化程序。 (或者在处理您的JSON时只需参考post['children']: - )

希望有助于您朝着正确的方向前进


其次是,如果你想要同一模型的不同表示,那么使用第二个ModelResource。显然,您可以继承子类以避免重复。

答案 1 :(得分:0)

您可以尝试覆盖alter_detail_data_to_serialize方法。它在整个对象脱水后立即调用,因此您可以在生成的字典序列化之前对其进行修改。

class PostResource(ModelResource):
    children = fields.ToManyField('MyApp.api.resources.PostResource',
             attribute='comments', full=True, null=True)

    def alter_detail_data_to_serialize(self, request, data):
        return data.get('children', [])

对于同一型号的不同表示 - 是的。基本上,你不应该让一个Resource有多个表示形式,因为这会导致歧义并且很难维护。