我正在开发 Django Rest Framework (DRF) 项目,其中我需要验证用户名字段并处理序列化器中的自定义更新逻辑。我的模型有一个用户名字段,其 unique=True。相关设置如下:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
class CustomUserSerializer(serializers.ModelSerializer):
class Meta:
model = models.CustomUser
fields = ["id", "username", "first_name", "last_name"]
read_only_field = ["id"]
extra_kwargs = {
"password": {"write_only": True},
}
def validate_username(self, value):
print('here.......')
user_model = get_user_model()
request = self.context.get('request')
if request and request.method in ['PUT', 'PATCH']:
if user_model.objects.filter(username=value).exclude(id=self.instance.id).exists():
raise serializers.ValidationError('User with this username already exists.')
else:
if user_model.objects.filter(username=value).exists():
raise serializers.ValidationError('User with this username already exists.')
return value
class CustomUserProfileSerializer(serializers.ModelSerializer):
user = CustomUserSerializer()
roles = ProfileRolesSerializer(many=True)
department = DepartmentSerializer()
gender = GenderSerializer()
class CustomUpdateView(APIView):
def put(self, request, *args, **kwargs):
serializer = CustomUserProfileSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
当我发送 PUT 请求来更新用户配置文件时,序列化器中的 validate_username 和 update 方法不会执行。相反,我收到响应错误:
{
"user": {
"username": [
"User with this username already exists."
]
}
}
我怀疑用户名字段上的默认 unique=True 约束绕过了序列化器级别的验证。 我试过了:
可能导致此问题的原因是什么?如何确保在 PUT 请求期间调用 validate_username 和 update 方法?
您应该避免将
CustomUserSerializer
嵌套在 CustomUserProfileSerializer
内。
而是在CustomUserProfileSerializer的update方法中单独处理user字段。此外,将用户名验证逻辑从 CustomUserSerializer 移至 CustomUserProfileSerializer,以确保正确处理更新。