Search code examples
djangotastypie

Tastypie - Queryset or filters


Im using tastypie and i just ran into a problem.

My problem:

Users can post messages and if other users are subscribed to that user they can see those message on their homepage. Its exactly like twitter users tweeting and followers looking at their tweets.

I have a public api for all messages.
I can filter a particular users messages using ?userid=1

Bad solution to problem:
I can filter multiple users messages (and thus solve the problem) using
?userid__in=1&userid__=5&...

But this is not a good way because the url length is going to increase to a possibly unallowed amount. (2000 characters)

Is there a better way of doing this?
Is there a way I can use request.user in a queryset to do a join?
Or should I use some sort of advanced filtering?

Thank YOU!


Solution

  • Tastypie already supports this via __in filtering (everything that ORM supports Tastypie exposes, except negations). No coding is necessary.

    Look here: http://django-tastypie.readthedocs.org/en/v0.9.11/resources.html#basic-filtering

    path/to/api/resource/?user_id__in=1,2,3,4,5,6
    

    However, you can still have the problem of your URL becoming huge with someone subscribed to many users. What you can do instead is keep this information in the DB model (which user is subscribed to which user as a recursive ManyToMany relationship within the model through a separate joint model).

    Then you could expose this through your resource without ever having to specify subscriptions through your URL as a parameter and/or filter. Instead your base queryset in the resource would be:

    userids = request.user.subscription_userset.values(id)
    

    provided that you have a self ManyToManyRelationship in your User model. Look here, and here.