Loading

序列化器中拿到request

image

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:]
posted @ 2024-10-06 18:01  一只大学生  阅读(3)  评论(0编辑  收藏  举报