Reputation: 5056
How can I do some processing before returning something through Tastypie for a specific user?
For example, let's say I have an app where a user has posts and can also follow other people's posts. I'd like to combine this person's posts with the posts of people they're following and return it as one array.
So let's say that in Tastypie I'd like to get the latest 20 posts from this person's timeline: I'd need to get the user, process this information and return it in JSON, but I'm not exactly sure how I'd process this and return it using Tastypie.
Any help?
Upvotes: 0
Views: 2734
Reputation: 196
Do more complex processing in get_object_list. It gets called before the dehydration process starts, i.e., before the JSON is created that gets passed back.
class PostResource(ModelResource):
class Meta:
queryset = Post.objects.all()
def get_object_list(self, request):
this_users_posts = super(PostResource, self).get_object_list(request).filter(user=User.objects.get(user=request.user))
all_the_posts_this_user_follows = super(PostResource, self).get_object_list(request).filter(follower=User.objects.get(user=request.user))
return this_users_posts | all_the_posts_this_user_follows
You need to fix those queries so that they work for your particular case. Then the trick is to combine the two different querysets you get back by concatenating them. Using | gets their full set, using & only gets their overlap. You want the full set (unless users can also follow their own posts, then you can probably call distinct() on the resulting superset).
Upvotes: 3