[Django]-How to expose manytomany field as a resource with tastypie?

1đź‘Ť

âś…

The solution can be quite simple.

You could implement a regular resource (forgetting about user ownership) and then follow the “Creating per-user resources” section of Tastypie cookbook to narrow the list returned by GET and ensure that the newly created objects are owned by the current user (POST).

With respect to PUT, you just need authorization class which ensures the user is only authorized to update his/her own goals. This is the trickiest part (but not hard), just make sure that the value of user attribute of the goal bundle is the same a request.user when the method is PUT otherwise raise an exception and you’re done 🙂

So with above you’d have following URIs:

GET,POST,PUT /api/users/ #for interaction with Users
GET,POST,PUT /api/user-goals/ #for interaction with Goals

and you could introduce (for GET):

GET /api/users/goals/ #for displaying user goals in more natural way

by following Nested Resources section of the cookbook

👤kgr

Leave a comment