0

假设我有如下资源..

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

2 回答 2

0

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

通常你会在dehydrate. 请参阅美味的食谱

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'因为美味的序列化程序正在寻找序列化字典而不是列表。

# "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

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

希望这可以帮助您朝着正确的方向前进


其次,是的,如果您想要同一模型的不同表示,请使用第二个ModelResource. 显然,您可以进行子类化以尝试避免重复。

于 2013-10-07T14:31:23.897 回答
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有很多表示,因为这会导致歧义并且难以维护。

于 2013-10-07T18:47:24.680 回答