Django:在模型save()方法中返回序列化程序ValidationError [英] Django: Return serializer ValidationError in Model save() method

查看:222
本文介绍了Django:在模型save()方法中返回序列化程序ValidationError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用django-rest-framework在Django框架内创建Rest API。除了序列化程序方法之外,还可能返回任何 validationError



但是,我想知道是否有可能返回错误从django 模型 save()方法转换为django rest validationError 的方法?



例如,假设我想限制在特定表上创建对象。像这样:

  class CustomTable(models.Model):
...#modles字段在这里

def save():如果CustomTable.objects.count()> 2:
#在连接到该模型的任何序列化器中返回一个validationError。

注意我可以使用 raise ValueError raise ValidationError ,但它们都会在端点上引起500错误。但是我想在我的api视图中返回一个响应,说例如已达到限制

解决方案

DRF ValidationError 在序列化程序中处理,因此在调用模型的save方法并使用它引发 ValiddationError 时,您应该捕获任何预期的错误。 / p>

例如,您可以在序列化程序的保存方法中执行以下操作:

  def save(self,** kwargs):
try:
super()。save(** kwargs)
除了ModelError以外,例如e:
提高serializers.ValidationError(e )

其中 ModelError 是您的错误,在模型中重新筹集资金


I use django-rest-framework to create Rest API within Django framework. And it's possible to return any validationError beside serializer methods.

But, I was wondering is it possible to return errors from save() method of django model that be translated to django rest validationError?

For example imagine I want to limit creating objects on a specific table. like this:

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.

Note I could use raise ValueError or raise ValidationError, but they all cause 500 error on endpoint. But i want to return a response in my api view that says for example 'limit reached'

解决方案

The DRF ValidationError is handled in the serializer so you should catch any expected errors when calling your model's save method and use it to raise a ValiddationError.

For example, you could do this in your serializer's save method:

def save(self, **kwargs):
    try:
        super().save(**kwargs)
    except ModelError as e:
        raise serializers.ValidationError(e)

Where ModelError is the error you're raising in your model

这篇关于Django:在模型save()方法中返回序列化程序ValidationError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆