Loading

drf中序列化器的钩子

1.对于ModelSerializer
使用写入钩子为validate
返回钩子get,字段得为SerializerMethodField()

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:]

image

2.1.对于Serializer

image

posted @ 2024-10-04 23:08  一只大学生  阅读(3)  评论(0编辑  收藏  举报