Django:模型 save() 方法中的 Return 序列化器 ValidationError
Django: Return serializer ValidationError in Model save() method
我使用 django-rest-framework 在 Django 框架内创建 Rest API。并且可以 return 除了序列化程序方法之外的任何 validationError
。
但是,我想知道是否有可能将 django save()
方法的 return 错误 model 转换为 django rest validationError
?
例如,假设我想限制在特定 table 上创建对象。像这样:
class CustomTable(models.Model):
... # modles fields go here
def save():
if CustomTable.objects.count() > 2:
# Return a validationError in any serializer that is connected to this model.
注意 我可以使用 raise ValueError
或 raise ValidationError
,但它们都会在端点上导致 500 错误。但我想在我的 api 视图中 return 做出回应,例如 'limit reached'
DRF ValidationError
在序列化程序中处理,因此您应该在调用模型的保存方法并使用它引发 ValiddationError
.
时捕获任何预期的错误
例如,您可以在序列化程序的保存方法中执行此操作:
def save(self, **kwargs):
try:
super().save(**kwargs)
except ModelError as e:
raise serializers.ValidationError(e)
其中 ModelError
是您在模型中引发的错误
有两到三种方法可以做到这一点
1.Using clean 方法。
class CustomTable(models.Model):
... # modles fields go here
def clean(self):
if CustomTable.objects.count() > 2:
raise ValidationError(_('custom table can not have more than two entries.'))
使用Signals。
@receiver(pre_save, sender= CustomTable)
def limit(sender, **kwargs):
if CustomTable.objects.count() > 2:
raise ValidationError(_('Custom table can not have more than two entries.'))
我使用 django-rest-framework 在 Django 框架内创建 Rest API。并且可以 return 除了序列化程序方法之外的任何 validationError
。
但是,我想知道是否有可能将 django save()
方法的 return 错误 model 转换为 django rest validationError
?
例如,假设我想限制在特定 table 上创建对象。像这样:
class CustomTable(models.Model):
... # modles fields go here
def save():
if CustomTable.objects.count() > 2:
# Return a validationError in any serializer that is connected to this model.
注意 我可以使用 raise ValueError
或 raise ValidationError
,但它们都会在端点上导致 500 错误。但我想在我的 api 视图中 return 做出回应,例如 'limit reached'
DRF ValidationError
在序列化程序中处理,因此您应该在调用模型的保存方法并使用它引发 ValiddationError
.
例如,您可以在序列化程序的保存方法中执行此操作:
def save(self, **kwargs):
try:
super().save(**kwargs)
except ModelError as e:
raise serializers.ValidationError(e)
其中 ModelError
是您在模型中引发的错误
有两到三种方法可以做到这一点
1.Using clean 方法。
class CustomTable(models.Model):
... # modles fields go here
def clean(self):
if CustomTable.objects.count() > 2:
raise ValidationError(_('custom table can not have more than two entries.'))
使用Signals。
@receiver(pre_save, sender= CustomTable) def limit(sender, **kwargs): if CustomTable.objects.count() > 2: raise ValidationError(_('Custom table can not have more than two entries.'))