简体   繁体   中英

Advanced Filtering in Tastypie

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?

Do more complex processing in get_object_list. It gets called before the dehydration process starts, ie, 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM