我想验证电子邮件ID,如果在注册前用户模型中已存在
这是我的验证序列化器
class RegistrationSerializer(serializers.Serializer):
username = serializers.CharField(max_length=100)
email = serializers.EmailField()
password = serializers.CharField(max_length=100)
def validate_email(self,attrs):
email=attrs['email']
print email
if email:
emailset = Q(email__icontains=email)
emailres = User.objects.filter(emailset)
if emailres:
msg = _('The email address is already taken')
raise serializers.ValidationError(msg)
else:
return attars
抛出错误" TypeError:字符串索引必须是整数"
email=attrs['email']
TypeError:字符串索引必须是整数
答案 0 :(得分:5)
我猜你已升级或使用DRF 3.x,因此不再有attrs
字典而是值。见field-level-validation
此外还有一个UniqueValidator。所以我认为你可以做到:
class RegistrationSerializer(serializers.Serializer):
#...
email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all())])