Prometheus
Prometheus

Reputation: 33625

Using dehydrate in Tastypie to return all objects

Reward.objects.get() returns an object, but how in Python/Django can I return all objects serialized for Tastypie?

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

i.e. above gives me <Reward object> and not a list of all the rewards.

Upvotes: 0

Views: 2272

Answers (2)

SteinOveHelset
SteinOveHelset

Reputation: 93

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

This works like a charm for me :)

Upvotes: 3

Justin O Barber
Justin O Barber

Reputation: 11591

If I understand you correctly, you want this:

rewards = Reward.objects.all()

instead of rewards = Reward.objects.get(). You can then iterate over the rewards query object to access the data in each row, if necessary. For example,

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)

Upvotes: 2

Related Questions