其更好地使用不同的viewsets爲
/users/{user-id} - PublicProfileViewset
/users/self - MyProfileViewSet
的原因是不同的權限和不同的查詢集兩個視圖集中交易。例如,PublicProfileViewset可以被任何沒有登錄的人訪問。但是MyprofileViewset只能由登錄用戶訪問。它類似於公開的個人資料和你自己的github個人資料。
對於PublicProfileViewset,
你可以簡單的使用路由器。不幸的是,我不知道如何將用戶的MyProfileViewset
這裏簡單的路由器的用戶對象是從request
對象本身採取像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'),
]