当序列化的时候 就会先走 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
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
标签:__,serializers,extra,ModelSerializer,jenkins,validate,序列化,class,Serializer From: https://www.cnblogs.com/kaibindirver/p/17140706.html