2013-10-07 20 views
0

假設我有一個資源像下面..如何僅返回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'] 

回答

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 

所以這表明你需要看看不同的序列化器。 (或者只是參考post['children']處理您的JSON :-)

希望幫助讓你在正確的方向


其次是的,如果你想同型號的不同表現,然後使用時第二個ModelResource。顯然你可以繼承以避免重複。

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有許多表示,因爲這會導致模糊性,並且難以維護。

相關問題