简体   繁体   中英

/users/self & /users/{id} route in Django Rest Framework

I currently have users routes using ModelViewSet for CRUD operations.

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

However, I would like to have endpoints similar to Instagram users: https://www.instagram.com/developer/endpoints/users/

  • /users/{user-id}
  • /users/self

both having the same CRUD ops, except one is to use request.user (if logged in).

How would I go about doing this? Using ModelViewSet and SimpleRouter?

Thanks.

Its better to use different viewsets for

/users/{user-id} - PublicProfileViewset
/users/self - MyProfileViewSet

The reason is both viewset deals with different permissions and different queryset. For eg PublicProfileViewset can be accessed by anyone without login. But MyprofileViewset should be accessed only by logged in user. Its similar to public profile and your own profile of github.

For PublicProfileViewset, you can simple use router. unfortunately, I don't know how to user simple routers for MyProfileViewset as here user object is taken from request object itself like request.user

views.py

class PublicUserProfileViewSet(viewsets.ReadOnlyModelViewSet):
    """
    Public end-points to get information about any user
    NOTE: All end-points provided here is read-only
    """

    queryset = User.objects.public()
    serializer_class = UserSerializer
    permission_classes = (permissions.AllowAny,)
    lookup_field = 'user_id'
    lookup_url_kwarg = 'pk'

class MyProfileViewSet(viewsets.ModelViewSet):
    """
    End-points to get all details about logged in user
    and update the profile of logged in user
    """
    queryset = User.objects.all()
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = UserSerializer

urls.py

router = routers.SimpleRouter()
router.register(r'users', PublicProfileViewSet)

urlpatterns = router.urls

urlpatterns += [
    url(r'^users/me/$', MyProfileViewSet.as_view(
        {'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'delete'}),
        name='myprofile'),
]

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