def list(self, request, *args, **kwargs): """ GET /api/comments/?tweet_id=1 重载 list 方法,不列出所有 comments,必须要求指定 tweet_id 作为筛选条件 """ # if 'tweet_id' not in request.query_params: # return Response({ # 'message': 'missing tweet_id in request', # 'success': False, # }, status=status.HTTP_400_BAD_REQUEST) # 利用 django_filter来filter queryset = self.get_queryset() comments = self.filter_queryset(queryset)\ .prefetch_related('user')\ .order_by('created_at') # tweet_id = request.query_params['tweet_id'] # comments = Comment.objects.filter(tweet_id=tweet_id).order_by('created_at') serializer = CommentSerializer( comments, context={'request': request}, many=True, ) return Response({'comments': serializer.data}, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs): # if 'tweet_id' not in request.query_params: # return Response( # { # 'message': 'missing tweet_id in request', # 'success': False, # }, # status=status.HTTP_400_BAD_REQUEST, # ) queryset = self.get_queryset() comments = self.filter_queryset(queryset)\ .prefetch_related('user')\ .order_by('created_at') # tweet_id = request.query_params['tweet_id'] # comments = Comment.objects.filter(tweet_id=tweet_id) serializer = CommentSerializer( comments, context={'request':request}, many=True, ) return Response( {'comments': serializer.data}, status=status.HTTP_200_OK, )
def create(self, request, *args, **kwargs): data = { 'user_id': request.user.id, 'tweet_id': request.data.get('tweet_id'), 'content': request.data.get('content'), } # Here must have 'data=' to assign params to data # because the first default param is 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) # the save() method would trigger create() method in serializer, click # into save() to see its implementation. comment = serializer.save() NotificationService.send_comment_notification(comment) return Response( CommentSerializer(comment, context={ 'request': request }).data, status=status.HTTP_201_CREATED, )
def update(self, request, *args, **kwargs): # feed the comment instance to the serializer to update # if not feed instance, serializer create object comment = self.get_object() serializer = CommentSerializerForUpdate( data=request.data, instance=comment, ) # validate the input of the update if not serializer.is_valid(): return Response( { 'success': False, 'message': 'Invalid Comment Update Input', 'error': serializer.errors, }, status=status.HTTP_400_BAD_REQUEST) # save the update updated_comment = serializer.save() serializer = CommentSerializer( instance=updated_comment, context={'request': request}, ) return Response(serializer.data, status=status.HTTP_200_OK)
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() NotificationService.send_comment_notification(comment) return Response( CommentSerializer(comment, context={ 'request': request }).data, status=status.HTTP_201_CREATED, )
def update(self, request, *args, **kwargs): # get_object 是 DRF 包装的一个函数,会在找不到的时候 raise 404 error # 所以这里无需做额外判断 comment = self.get_object() serializer = CommentSerializerForUpdate( instance=comment, data=request.data, ) if not serializer.is_valid(): return Response( { 'success': False, 'message': 'Please check input.', 'errors': serializer.errors, }, status=status.HTTP_400_BAD_REQUEST) # save 方法会触发 serializer 里的 update 方法,点进 save 的具体实现里可以看到 # save 是根据 instance 参数有没有传来决定是触发 create 还是 update comment = serializer.save() return Response( CommentSerializer(comment, context={ 'request': request }).data, status=status.HTTP_200_OK, )
class TweetSerializerWithComments(serializers.ModelSerializer): user = UserSerializer comments = CommentSerializer(source='comment_set', many=True) class Meta: model = Tweet fields = ('id', 'user', 'comments', 'created_at', 'content')
def create(self, request, *args, **kwargs): data = { 'user_id': request.user.id, 'tweet_id': request.data.get('tweet_id'), 'content': request.data.get('content'), } # validate the input by CommentSerializerForCreate serializer = CommentSerializerForCreate(data=data) if not serializer.is_valid(): return Response( { 'success': False, 'message': 'Invalid Comment Input', 'error': serializer.errors, }, status=status.HTTP_400_BAD_REQUEST) # save validated comment comment = serializer.save() # raise notification for comment creation NotificationService.send_comment_notification(comment) serializer = CommentSerializer( instance=comment, context={'request': request}, ) return Response(serializer.data, status=status.HTTP_201_CREATED)
class TweetSerializerWithComments(serializers.ModelSerializer): user = UserSerializer() # <HOMEWORK> 使用 serialziers.SerializerMethodField 的方式实现 comments comments = CommentSerializer(source='comment_set', many=True) class Meta: model = Tweet fields = ('id', 'user', 'comments', 'created_at', 'content')
def list(self, request, *args, **kwargs): queryset = self.get_queryset() comments = self.filter_queryset(queryset).prefetch_related('user') serializer = CommentSerializer(comments, many=True) return Response({'comments': serializer.data})
def get_comments(self, obj): c_qs = Comment.objects.filter(article__articleid=obj.articleid) comments = CommentSerializer(c_qs, context={ 'request': None }, many=True).data return comments
class PostSerializer(serializers.ModelSerializer): user = UserSerializer() comments = CommentSerializer(many=True) class Meta: model = Post fields = [ 'title', 'id', 'user', 'content', 'image', 'timestamp', 'comments' ]
class SpotSerializer(ModelSerializer): attractions = AttractionSerializer(many=True) comments = CommentSerializer(many=True) review = ReviewSerializer(many=True) localization = LocalizationSerializer() class Meta: model = Spot fields = '__all__'
def list(self, request, *args, **kwargs): queryset = self.get_queryset() comments = self.filter_queryset(queryset).order_by('created_at') serializer = CommentSerializer( comments, context={'request': request}, many=True, ) return Response({'comments': serializer.data}, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs): # will return queryset, get_querySet() could be override queryset = self.get_queryset() # filter by filterset_fields comments = self.filter_queryset(queryset).order_by('created_at') serializer = CommentSerializer(comments, many=True) return Response( {'comments': serializer.data}, status=status.HTTP_200_OK, )
def list(self, request, *args, **kwargs): # filter comments by tweet_id, and order comments by created_at time queryset = self.get_queryset() comments = self.filter_queryset(queryset) serializer = CommentSerializer(instance=comments, context={'request': request}, many=True) return Response({ 'success': True, 'comments': serializer.data, }, status=status.HTTP_200_OK)
class CompletePontoTuristicoSerializer(serializers.ModelSerializer): attraction_list = AttractionSerializer(many=True) location = LocationSerializer() review_list = ReviewSerializer(many=True) comment_list = CommentSerializer(many=True) class Meta: model = PontoTuristico fields = [ 'id', 'name', 'description', 'status', 'location', 'attraction_list', 'comment_list', 'review_list' ]
class TouristSpotSerializer(ModelSerializer): attractions = AttractionSerializer(many=True) comments = CommentSerializer(many=True) reviews = ReviewSerializer(many=True) address = AddressSerializer() full_description = serializers.SerializerMethodField() class Meta: model = TouristSpot fields = ['id', 'name', 'description', 'okay', 'attractions', 'comments', 'reviews', 'address', 'photo', 'full_description'] def get_full_description(self, obj): return '%s - %s ' % (obj.name, obj.description)
def update(self, request, *args, **kwargs): serializer = CommentSerializerForUpdate( instance=self.get_object(), data=request.data, ) if not serializer.is_valid(): return Response({ 'message': 'Please check input' }, status=status.HTTP_400_BAD_REQUEST) comment = serializer.save() return Response( CommentSerializer(comment, context={'request': request}).data, status=status.HTTP_200_OK, )
def update(self, request, *args, **kwargs): serializer = CommentSerializerForUpdate( instance=self.get_object(), data=request.data ) if not serializer.is_valid(): return Response({ "success": False, "message": "Please check inputs.", "errors": serializer.errors, }, status=HTTP_400_BAD_REQUEST) comment = serializer.save() return Response(CommentSerializer(comment).data, status=HTTP_200_OK)
def list(self, request, *args, **kwargs): queryset = self.get_queryset() # optimization, prefetch 和 select_related == join comments = self.filter_queryset(queryset).prefetch_related( 'user').order_by('created_at') serializer = CommentSerializer( comments, context={'request': request}, many=True, ) return Response( {'comments': serializer.data}, status=status.HTTP_200_OK, )
def list(self, request, *args, **kwargs): queryset = self.get_queryset() # this is related to the django_filter backend # 下面这句话为了提高效率用prefetch_related, 也可以用select_related('user'), 但是select_related 会有join 不好 comments = self.filter_queryset(queryset) \ .prefetch_related('user') \ .order_by('created_at') serializer = CommentSerializer( comments, context={'request': request}, many=True, ) return Response( {'comments': serializer.data}, status=status.HTTP_200_OK, )
class TouristSpotSerializer(ModelSerializer): attractions = AttractionSerializer(many=True, read_only=True) address = AddressSerializer() comments = CommentSerializer(many=True) reviews = ReviewSerializer(many=True) complete_description = SerializerMethodField() class Meta: model = TouristSpot fields = ('id', 'name', 'description', 'approved', 'photo', 'attractions', 'comments', 'reviews', 'address', 'complete_description', 'complete_description2') def get_complete_description(self, obj): return '%s - %s' %(obj.name, obj.description)
def update(self, request, *args, **kwargs): # get_object will raise 404 error if not found serializer = CommentSerializerForUpdate( instance=self.get_object(), data=request.data, ) if not serializer.is_valid(): raise Response({'message': 'Please check input'}, status=status.HTTP_400_BAD_REQUEST) comment = serializer.save() return Response( CommentSerializer(comment).data, status=status.HTTP_200_OK, )
def list(self, request, *args, **kwargs): if 'tweet_id' not in request.query_params: return Response( { 'message': 'missing tweet_id in the request', 'success': False }, status=status.HTTP_400_BAD_REQUEST) comments = self.filter_queryset( self.get_queryset()).order_by('created_at') serializer = CommentSerializer(comments, context={'request': request}, many=True) return Response({'comments': serializer.data}, status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs): # get_object is DRF wrapped method, raise 404 error when cannot find serializer = CommentSerializerForUpdate( instance=self.get_object(), data=request.data, ) if not serializer.is_valid(): return Response({ 'message': 'Please check input.' }, status=status.HTTP_400_BAD_REQUEST) # save() will trigger update() # save() depends on instance has param or not to decide create() or update() comment = serializer.save() return Response( CommentSerializer(comment, context={'request': request}).data, status=status.HTTP_200_OK, )
class TweetSerializerForDetail(TweetSerializer): comments = CommentSerializer(source='comment_set', many=True) likes = LikeSerializer(source='like_set', many=True) class Meta: model = Tweet fields = ( 'id', 'user', 'created_at', 'content', 'likes', 'comments', 'comments_count', 'likes_count', 'has_liked', )
def update(self, request, *args, **kwargs): # get_object is a wrapped function in DRF, will raise 404 error when the object cannot be found # so no need to do extra check whether the comment object exists serializer = CommentSerializerForUpdate( instance=self.get_object(), data=request.data, ) if not serializer.is_valid(): return Response({ 'message': 'Please check input', }, status=status.HTTP_400_BAD_REQUEST) # save will trigger the update method of the serializer # whether to trigger create() or update() depends on the existence of the parameter instance comment = serializer.save() return Response( CommentSerializer(comment, context={'request': request}).data, status=status.HTTP_200_OK, )
def list(self, request, *args, **kwargs): # tweet_id = request.query_params['tweet_id'] # comments = Comment.objects.filter(tweet_id=tweet_id) # serializer = CommentSerializer(comments, many=True) # return ... queryset = self.get_queryset() # Here use prefetch_related('user') to reduce sql queries comments = self.filter_queryset(queryset)\ .prefetch_related('user')\ .order_by('created_at') serializer = CommentSerializer( comments, context={'request': request}, many=True, ) return Response( {'comments': serializer.data}, status=status.HTTP_200_OK, )