class UpdateMobileSerializer(serializers.ModelSerializer):
old = serializers.CharField(write_only=True, validators=[RegexValidator(r"\d{11}", message="格式错误")])
mobile = serializers.CharField(write_only=True, validators=[RegexValidator(r"\d{11}", message="格式错误")])
new_mobile = serializers.SerializerMethodField(read_only=True)
class Meta:
model = models.Company
fields = ['old', "mobile", "new_mobile"]
def validate_old(self, val):
# 当前登录用的手机号是不是
request = self.context['request']
user_id = request.user['id']
exists = models.Company.objects.filter(id=user_id, mobile=val).exists()
if not exists:
raise ValidationError("原手机号错误")
return val
def validate_mobile(self, val):
# 新手机号,已存在
exists = models.Company.objects.filter(mobile=val).exists()
if exists:
raise ValidationError("该手机已注册")
return val
def get_new_mobile(self, obj):
return obj.mobile[0:3] + "****" + obj.mobile[-4:]
标签:serializers,exists,val,mobile,request,器中,序列化,id
From: https://www.cnblogs.com/cloud-2-jane/p/18449243