def create(self, request, *args, **kwargs): data = { 'user_id': request.user.id, 'tweet_id': request.data.get('tweet_id'), 'content': request.data.get('content'), } serializer = CommentSerializerForCreate(data=data) if not serializer.is_valid(): return Response( { 'message': 'Please check input', 'errors': serializer.errors }, status=status.HTTP_400_BAD_REQUEST) comment = serializer.save() NotificationService.send_comment_notification(comment) return Response( CommentSerializer(comment, context={ 'request': request }).data, status=status.HTTP_201_CREATED, )
def create(self, request, *args, **kwargs): data = { 'user_id': request.user.id, 'tweet_id': request.data.get('tweet_id'), 'content': request.data.get('content'), } # 注意这里必须要加 'data=' 来指定参数是传给 data 的 # 因为默认的第一个参数是 instance serializer = CommentSerializerForCreate(data=data) if not serializer.is_valid(): return Response( { 'message': 'Please check input', 'errors': serializer.errors, }, status=status.HTTP_400_BAD_REQUEST) # save 方法会触发 serializer 里的 create 方法,点进 save 的具体实现里可以看到 comment = serializer.save() return Response( CommentSerializer(comment).data, status=status.HTTP_201_CREATED, )