Django: Return serializer ValidationError in Model save() method

最后都变了- 提交于 2020-01-15 09:36:09

问题


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'


回答1:


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




回答2:


There's are two to three ways to do this

1.Using clean method.

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.'))
  1. Using 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.'))
    


来源:https://stackoverflow.com/questions/54061030/django-return-serializer-validationerror-in-model-save-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!