目前,我已经制作了一个“赞”模型,并分别通过发布和删除请求实现了“赞”和“不喜欢”。因此,在实现了Like之后,我想实现Like,并且我知道为了实现它,我必须选择该Like对象的pk,将其映射到url,然后向该url发送删除请求。但是,此方法需要同时使用名为“ / post_id / like / like_id”和“ / post_id / like_id”的网址,但我并没有这样做,但是当删除请求得到解决时,请尝试从视图重定向到“ / post_id / like / like_id”发送到称为“ / post_id / like / like”的网址。我怎样才能使逻辑继续进行我认为的代码?这是我的代码。
views.py
class CreateReadLikeView (ModelViewSet) :
serializer_class = LikeSerializer
permission_classes = [IsAuthenticated]
queryset = Like.objects.all()
is_saved = False
def get_queryset (self) :
return super().get_queryset().filter(post=self.kwargs.get('post_id'))
def perform_create (self, serializer) :
postId = self.kwargs.get('post_id')
post = Post.objects.get(pk=postId)
try :
like = self.queryset.get(post=post, liked_people=self.request.user)
except Like.DoesNotExist :
serializer.save(liked_people=self.request.user, post=post)
self.is_saved = True
def create (self, request, *args, **kwargs) :
super().create(request, *args, **kwargs)
if self.is_saved is True :
self.is_saved = False
return Response({'success': '해당 게시물을 좋아요 했습니다.'}, status=200)
return Response({'message': ['이미 해당 게시물을 좋아요 하였습니다.']}, status=400)
def list (self, request, *args, **kwargs) :
postId = self.kwargs.get('post_id')
post = Post.objects.get(pk=postId)
try :
like = self.queryset.get(post=post, liked_people=self.request.user)
except Like.DoesNotExist :
return Response({'message': ['좋아요 하지 않음.']}, status=400)
return Response({'success': '좋아요함.'}, status=200)
class DeleteLikeView (ModelViewSet) :
serializer_class = LikeSerializer
permission_classes = [IsAuthenticated, IsLiker]
queryset = Like.objects.all()
def get_queryset (self) :
return super().get_queryset().filter(post=self.kwargs.get('post_id'))
def destroy (self, request, *args, **kwargs) :
super().destroy(request, *args, **kwargs)
return Response({'success': '해당 게시물의 좋아요를 취소했습니다.'}, status=200)
urls.py
path('post/<int:post_id>/like', CreateReadLikeView.as_view({'post': 'create', 'get': 'list', 'delete': 'destroy'})), # If a delete request is sent to this url.
path('post/<int:post_id>/like/<int:pk>', DeleteLikeView.as_view({'delete': 'destroy'})), # I want to redirect this url.