0

我有一个带有字段的类评论:分数,作者,Id,pub_date 这是我在序列化程序中的代码

class CommentSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(read_only=True,slug_field='username')
    class Meta:
        fields = ('id','text','author','score', 'pub_date')
        model = Comment

意见:

class CommentViewSet(ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = [MyPermissionClass]
    pagination_class = MyLimitOffsetPagination
    def get_queryset(self):
        post = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
        return post.comment_set
    def perform_create(self, serializer):
        post = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
        a=serializer(author=self.request.user, post=post)
   if a.score<50: 
       a.save()
   else: 
       Response({'number':'must be less than 50'}, status=status.HTTP_400_BAD_REQUEST)

但它不起作用,它不仅没有将score的值限制为50,而且还破坏了整个代码

4

1 回答 1

0

我认为您正在寻找的是 DRF Link to docs的整数字段的最大值验证

尝试

class CommentSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(read_only=True,slug_field='username')
    
    score = serializers.IntegerField(max_value=50, min_value=0)

    class Meta:
        fields = ('id','text','author','score', 'pub_date')
        model = Comment

或者由于您已经在使用模型序列化器,您可以提供这些作为该领域的额外 kwargs,

class CommentSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(read_only=True,slug_field='username')
    

    class Meta:
        fields = ('id','text','author','score', 'pub_date')
        model = Comment
        extra_kwargs = {
          "score": {"min_value": 0, "max_value": 50}
        }

注意我已将最小值添加为 0。

现在您可以简单地将您的视图视为

# importing Response 
from rest_framework.response import Response

class CommentViewSet(ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = [MyPermissionClass]
    pagination_class = MyLimitOffsetPagination

    def get_queryset(self):
        post = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
        return post.comment_set
  
    def perform_create(self, serializer):
        post = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
        a=serializer(author=self.request.user, post=post)

        # raise any validation error if any
        a.is_valid(raise_expection=True)    
        a.save()
        return Response(a)           
于 2021-03-03T15:27:22.033 回答