Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing "virtual" field in a tastypie view?

I want to create a view using tastypie to expose certain objects of the same type, but with the following two three twists:

  1. I need to get the objects using three separate queries;
  2. I need to add a field which doesn't exist in the underlying model, and the value of that field depends on which of the queries it came from; and
  3. The data will be per-user (so I need to hook in to one of the methods that gets a request).

I'm not clear on how to hook into the tastypie lifecycle to accomplish this. The recommended way for adding a "virtual" field is in the dehydrate method, which only knows about the bundle it's operating on.

Even worse, there's no official way to join querysets.

My problem would go away if I could get tastypie to accept something other than a queryset. In that case I could pass it a list of subclasses of my object, with the additional field added.

I'm open to any other sensible solution.

Edit: Added twist 3 - per-user data.

like image 688
Marcin Avatar asked Dec 04 '22 21:12

Marcin


1 Answers

In the last version you should override the dehydrate method, e.g.

def dehydrate(self, bundle):
    bundle.data['full_name'] = bundle.obj.get_full_name()
    return bundle
like image 141
matley Avatar answered Dec 26 '22 20:12

matley