2014-01-11 20 views
0

Reward.objects.get()返回一個對象,但是如何在Python/Django中返回序列化爲Tastypie的所有對象?在Tastypie中使用脫水返回所有對象

def dehydrate(self, bundle): 
    res = super(SchemeResource, self).obj_update(bundle) 
    rewards = Reward.objects.get() 
    bundle.data['reward_participants'] = rewards 
    return res 

即上述給我<Reward object>而不是所有獎勵的清單。

+0

我想你問的是一個對象的字典中返回的嘗試[ST .__在獎勵dict__爲ST] –

+0

也看到這裏:http://stackoverflow.com/questions/13565975/convert-a-queryset-to-json-using-tastypie-resource –

回答

2

如果我理解正確的話,你想這樣:

rewards = Reward.objects.all() 

,而不是rewards = Reward.objects.get()。如有必要,您可以遍歷獎勵查詢對象以訪問每行中的數據。例如,

rewards = Reward.objects.all() 
rewards = [(x.id, x.name) for x in rewards] # returns a list of tuples for the id and name fields (if such fields exist) 
+0

即使與'所有'在JSON Tastypie仍然只顯示<獎勵對象> for每一個:( – Prometheus

+0

@Spike你必須遍歷才能訪問它的內容,例如,r中的[(r.id,r.name)]將返回一個元組列表用id和name字段值(或者用你所有的字段替換這兩個字段)。 –

3
def dehydrate(self, bundle): 
    res = super(SchemeResource, self).obj_update(bundle) 
    rewards = Reward.objects.all() 
    bundle.data['reward_participants'] = [model_to_dict(r) for r in rewards] 
    return res 

這就像一個魅力對我來說:)

+0

請解釋一下model_to_dict是什麼。 –

+1

@MikeStoddart model_to_dict是一個將查詢集變成Python字典的函數 – SteinOveHelset