Home:ALL Converter>Django: Return serializer ValidationError in Model save() method

Django: Return serializer ValidationError in Model save() method

Ask Time:2019-01-06T19:26:46         Author:Reza Torkaman Ahmadi

Json Formatter

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'

Author:Reza Torkaman Ahmadi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/54061030/django-return-serializer-validationerror-in-model-save-method
Ken4scholars :

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.\nFor example, you could do this in your serializer's save method:\ndef save(self, **kwargs):\n try:\n super().save(**kwargs)\n except ModelError as e:\n raise serializers.ValidationError(e)\n\nWhere ModelError is the error you're raising in your model",
2019-01-06T12:22:46
yy