我正在尝试用django(DRF)编写视图,该视图允许用户在帖子上添加赞,在帖子上更新赞状态(赞/不喜欢),并删除帖子上的赞。帖子ID在参数中发送,用户ID从auth令牌中提取。
我想出了如何进行前两个操作,但我不知道如何进行更新。到目前为止,这是我的看法:
class LikeView(generics.CreateAPIView, UpdateModelMixin, DestroyModelMixin):
serializer_class = LikeSerializer
queryset = Like.objects.all()
lookup_field = 'post'
permission_classes = [IsAuthenticated]
def get_object(self):
post = self.request.query_params.get('post')
user = self.request.user.id
return self.get_queryset().filter(post=post, user=user)
# retrieve user ID from token, validate data and save the like on post (working)
def post(self, request, *args, **kwargs):
data = self.get_data(request)
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response('Like has been saved')
def put(self, request, *args, **kwargs):
data = self.get_data(request)
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
# working
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
# add the data from param and token to a copy of the request body
# to use with the serializers
def get_data(self, request):
data = request.data.copy()
data['post'] = self.request.query_params.get('post')
data['user'] = request.user.id
return data
像模型:
class Like(models.Model):
user = ForeignKey(User, on_delete=models.CASCADE)
post = ForeignKey(Post, on_delete=models.CASCADE)
state = BooleanField(
default=True, help_text='Like = True, Dislike = False')
created_at = DateTimeField(auto_now_add=True)
updated_at = DateTimeField(auto_now=True)
def __str__(self):
state_int = int(self.state)
return ['Dislike', 'Like'][state_int]
class Meta:
unique_together = ('user', 'post')
我在这里做错了什么? put
处理程序缺少什么?
答案 0 :(得分:1)
您错过了为 {{1}]中的 instance
提供 serializer
参数} 方法。
put
答案 1 :(得分:0)
首先,您不会从此方法返回任何值。
def put(self, request, *args, **kwargs):
data = self.get_data(request)
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
尝试添加
return Response('Like has been updated')
第二,您需要将实例传递给序列化器:
data = self.get_data(request)
instance = self.get_queryset().get(user_id=request.user.id, post_id=request.data['post_id'])
serializer = self.get_serializer(instance=instance, data=data)
如果它不起作用,请报告确实不起作用。