【问题标题】:Using dehydrate in Tastypie to return all objects在 Tastypie 中使用 dehydrate 返回所有对象
【发布时间】:2014-01-11 20:05:21
【问题描述】:

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>,而不是所有奖励的列表。

【问题讨论】:

标签: python django tastypie


【解决方案1】:
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

这对我来说就像一个魅力:)

【讨论】:

  • 请解释一下什么是model_to_dict。
  • @MikeStoddart model_to_dict 是将查询集转换为 python 字典的函数
【解决方案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)

【讨论】:

  • 即使在 json 中使用 'all' Tastypie 仍然只为每个显示 :(
  • @Spike 您必须遍历 才能访问其内容。例如,[(r.id, r.name) for r in reward] 将返回具有 id 和 name 字段值的元组列表(或将这两个字段替换为您拥有的任何字段)。
猜你喜欢
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
相关资源
最近更新 更多