Python 升级UserProfile序列化程序时出现完整性错误
我正在尝试创建一个更新Python 升级UserProfile序列化程序时出现完整性错误,python,django-rest-framework,Python,Django Rest Framework,我正在尝试创建一个更新序列化程序,并为异常集成错误返回一条消息 下面是特定代码行的片段- instance.username = validated_data.get('username', instance.username) if User.objects.filter(username__iexact=instance.username).exists(): raise BaseException 如果不使用Try和Except 更新- 这就是我解决这个问
序列化程序
,并为异常
集成错误
返回一条消息
下面是特定代码行的片段-
instance.username = validated_data.get('username', instance.username)
if User.objects.filter(username__iexact=instance.username).exists():
raise BaseException
如果不使用Try
和Except
更新-
这就是我解决这个问题的方法-
if User.objects.filter(username__iexact=instance.username).exists():
raise serializers.ValidationError("username already exists")
User.objects.filter(username\uu iexact=instance.username).exists()
这将不起作用,因为实例也是User
对象,因此它将始终返回True
,您需要首先排除当前实例
固定查询:
User.objects.exclude(pk=instance.pk).filter(username\uu iexact=instance.username).exists()
我不知道您为什么不想使用
try/catch
,但不管怎样,在遵循好的模式时,您可以做以下几点:
User
模型已经具有unique=True
约束save()
时抛出一个IntegrityError
IntegrityError
,然后引发序列化程序。ValidationError
从rest\u框架导入序列化程序、视图集
来自rest_framework.exceptions ValidationError
类UserProfileUpdateViewSet(ViewSet.ModelViewSet):
def执行_更新(自、序列化程序):
"""
覆盖该方法
"""
尝试:
serializer.save()
除完整性错误外:
引发验证错误(
f“用户名已被占用。请选择其他用户名。”,
)
你有没有试过把raise BaseException(“你想要的消息”)放进去?@jalazbe是的,我试过了,没什么区别。它返回的结果与发生服务器错误时的BaseException相同。请与管理员联系。