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/
Based on your code:
You are interpreting this in a wrong way. Here's how you can use
NestedSimpleRouter
This url:
is working because you are filtering by
owner = request.user
.And this url:
is supposed to give list of all comments by taking profile_id in
UserCommentViewSet
. So your view will be like: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:
and the
UserCommentViewSet
is:Then, this url:
will give all comments as required.