Serializer 序列化 之 validate 校验

当序列化的时候 就会先走 validate 方法

class JenkinsListSerializers(serializers.ModelSerializer):

    class Meta:
        model = tbl_jenkins_serve
        fields = ('id', 'jenkins_name')
        extra_kwargs = {
            'id': {
                'read_only': True,
            },
        }

    def validate(self, attrs):
        if tbl_jenkins_serve.objects.filter(jenkins_name=attrs['jenkins_name']).first():
            raise serializers.ValidationError('对应服务已存在')
        return attrs
    
    貌似还可以指定--有空试试 --已试可行
    def validate_jenkins_name(self, value):
        if tbl_user.objects.filter(username=value).first():
            raise serializers.ValidationError('用户名已存在')
        return value

 

extra_kwargs

我们可以使用 extra_kwargs 参数为 ModelSerializer 添加或修改原有的选项参数。   

from rest_framework import serializers
from .models import MyBook


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyBook
        fields = '__all__'

        extra_kwargs = {
            'title': {
            	'max_length': 8, 'min_length': 3, 
            	'error_messages': {'min_length': '太短了'}
            	}
        }

 

也可以直接写在下面,比如下面的title

from rest_framework import serializers
from .models import MyBook

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyBook
        fields = '__all__'

    title = serializers.CharField(max_length=99999)

 

参考: https://blog.csdn.net/m0_58987515/article/details/125285865

posted @ 2023-02-21 13:53  凯宾斯基  阅读(110)  评论(0编辑  收藏  举报