喜欢标题,
django-rest-framework中list_route
和detail_route
的不同之处是什么?
如果我想在网址1
中获取xxx/books/1/
,
如何撰写url.py
和views.py
?
答案 0 :(得分:1)
**阅读本文,肯定会有所不同,以及如何使用它**
如果我们有一个ad hoc方法(例如,当前方法与我们用于不同方法的视图集相同,基本上 ad-hoc意味着'这个'),我们可以使用自定义路由为这个方法,我们可以 在@list_route和@中的方法上面定义我们自己的url @detail_route装饰者
@ list_route和@detail_route之间的区别在于@detail_route装饰器在其URL模式中包含pk,适用于需要单个实例的方法。 @list_route装饰器适用于对象列表(记录列表)进行操作的方法
通过获取参考资料 enter link description here
例如
**It will hit to the same url at the url.py but for @list_raoute we have append /reset-user-password/ which we have mention on @list_route to the url when we call it.(e.g
/// In url.py**
router = routers.DefaultRouter()
router.register(r'register', api_views.UserProfileViewSet, base_name="userprofileviewset")
urlpatterns = [
url(r'^api/v1/', include(router.urls)),
]
** //////在API通话或网址调用中
用于创建用户**http://127.0.0.1:8000/api/v1/register/
###忘记密码
http://127.0.0.1:8000/api/v1/resister/reset-user-password/ )
class UserProfileViewSet(viewsets.ViewSet):
"""
IT's use to create new user(auth user). accepted method is post.
end point /register
"""
permission_classes = (AllowAny,)
serializer_class = UserProfileSerializer
"""
It gives the list of all users
"""
def list(self, request):
queryset = UserProfile.objects.all()
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
"""
It creates new user
"""
def create(self, request):
serializer = self.serializer_class(data=request.data)
# check email address is exists or not.
user_type = request.data['user_type']
user_token = register_by_social(request.data['email'], request.data['username'], user_type)
if not user_token or user_token == True:
if not User.objects.filter(Q(email=request.data['email'])
| Q(username=request.data['username'])).exists():
if serializer.is_valid():
userprofile = serializer.save()
return Response({
'status': status.HTTP_201_CREATED,
'message': 'Successfully signup new user.',
'token': userprofile.user.auth_token.key })
return Response({
'status': status.HTTP_400_BAD_REQUEST,
'message': 'Please provided required fields.',
'error' : serializer.errors })
return Response({
'status': status.HTTP_409_CONFLICT,
'message': 'Email address or username is already exists.'})
return Response({
'status': status.HTTP_200_OK,
'message': 'Social user is already registered.',
'token': user_token })
@list_route(permission_classes=[IsAuthenticated], authentication_classes = (BasicAuthentication, TokenAuthentication),
methods=['post'], url_path='reset-user-password')
def reset_user_password(self, request, pk=None):
"""
It resets the user password
"""
reset_password_serializer = UserResetPasswordSerializer(request.user, data=request.data)
if reset_password_serializer.is_valid():
if not request.user.check_password(request.data.get('password')):
return Response({
'status': status.HTTP_400_BAD_REQUEST,
'message': 'Password id wrong, please enter correct password',
})
request.user.set_password(request.data.get('new_password'))
request.user.save()
return Response({
'status': status.HTTP_201_CREATED,
'message': 'Password updated successfully',
})
class PlayListViewSet(viewsets.ViewSet):
permission_classes = (IsAuthenticated,)
serializer_class = PlayListSerializer
serializer_add_playlist_class = LikeContentSerializer
@detail_route(methods=['post'], url_path='add-content-to-playlist')
def add_playlist(self, request, pk=None):
serializer = self.serializer_add_playlist_class(data=request.data)
playlist = PlayList.objects.filter(id=pk)
if serializer.is_valid():
content_type = request.data['content_type']
if content_type =="audio":
content = Song.objects.filter(id=request.data['content'])
playlist[0].songs.add(content[0])
playlist[0].save()
if content_type =="video":
content = Video.objects.filter(id=request.data['content'])
playlist[0].videos.add(content[0])
playlist[0].save()
if content_type =="youtube":
content = YouTubeVideo.objects.filter(id=request.data['content'])
playlist[0].youtbue_videos.add(content[0])
playlist[0].save()
return Response({
'status': status.HTTP_201_CREATED,
'message': 'Successfully playlist updated'})
return Response({
'status': status.HTTP_400_BAD_REQUEST,
'message': 'Data is not valid, try again',
'error' : serializer.errors })
答案 1 :(得分:0)
detail_route,是一个实例。我的意思是,用细节路线生成的方法将在实例方法之后附加,即检索。 {前缀} / {查找} /
如果您的模型图书且 1 是ID:
class ParkingViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer
def retrieve(self, request, pk=None):
# Here pk will be 1.
queryset = Book.objects.get(pk=pk)
serializer = BookSerializer(queryset)
return Response({'msg':"",'data':serializer.data, 'status':'OK'})
如果xxx是您的实例,您应该使用url_path变量来更改默认网址。像这样:
@detail_route(methods=['get'], url_path='(books/?P<num>\d+)')
然后在该方法中,您将使用num作为参数
urls.py,将使用默认路由器生成:
from django.conf.urls import url, include
from recharge_card import views
from rest_framework.routers import DefaultRouter
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'xxx', views.XxxViewSet, base_name="xxx")
urlpatterns = [
url(r'^api/', include(router.urls)),
]