Reward.objects.get()
返回一个对象,但是如何在Python / Django中返回为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 :(得分: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
这对我来说就像是一种魅力:)
答案 1 :(得分: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)