NestedSimpleRouter without using lookup in router

1.8k views Asked by At

I am using drf-nested-router something like the following in my url.py

router = SimpleRouter()
profile_router = routers.NestedSimpleRouter(router, r'profile', lookup='user')
profile_router.register(r'comments', UserCommentViewSet, basename='profile-comments')

The viewset is

class UserCommentViewSet(CommentViewSet):
    def get_queryset(self):
        return Comment.objects.filter(owner=self.request.user)

So the URL is something like,

mydomain.com/profile/{profile_id}/comments/

it gives me right results. But the following URL is also giving me right results,

mydomain.com/profile/{anything}/comments/

because I am using the session user info to filter the data. Is it possible to make the URL like

mydomain.com/profile/comments/
1

There are 1 answers

11
Siva Sankar On

Based on your code:

router = SimpleRouter()
# router.register('users', UserViewSet, 'user')
profile_router = routers.NestedSimpleRouter(router, r'profile', lookup='user')
profile_router.register(r'comments', UserCommentViewSet, basename='profile-comments')

You are interpreting this in a wrong way. Here's how you can use NestedSimpleRouter

mydomain.com/profile/ # list all the users.
mydomain.com/profile/{profile_id} # retrieve particular user based on profile_id/user_id/pk.
mydomain.com/profile/{profile_id}/comments/ # list all the comments belong to a particular user (not the current session user) based on profile_id/user_id.
mydomain.com/profile/{profile_id}/comments/{comment_id} # retrieve particular comment based on comment_id.

This url:

mydomain.com/profile/{anything}/comments/

is working because you are filtering by owner = request.user.

And this url:

mydomain.com/profile/{profile_id}/comments/

is supposed to give list of all comments by taking profile_id in UserCommentViewSet. So your view will be like:

class UserCommentViewSet(CommentViewSet):
    def get_queryset(self):
        return Comment.objects.filter(owner__id=profile_id)

In simple words you can use NestedSimpleRouter to get all users, user detail, all comments posted by single user and comment detail.

Solution:

If you need only current (session) user comments (since you dont need all comments by all users), you need something like:

router = SimpleRouter()
router.register(r'profile/comments', UserCommentViewSet, basename='profile-comments')

and the UserCommentViewSet is:

class UserCommentViewSet(CommentViewSet):
    def get_queryset(self):
        return Comment.objects.filter(owner=self.request.user)

Then, this url:

mydomain.com/profile/comments/

will give all comments as required.