How to return an error message from the Model?

2019-08-05 07:00发布

In suppliment to this question, if business logic should be in the model, how do I return an error message from the model?

def save(self, *args, **kwargs):
    if <some condition>:
        #return some error message to the view or template

2条回答
Deceive 欺骗
2楼-- · 2019-08-05 07:43

Raising an exception is the way to report a program logic error (an error in 'business logic'), which is what you are talking about. You can just raise an Exception, as pastylegs proposes (be aware that SomeException is just a placeholder):

from django.core.exceptions import SomeException

def save(self, *args, **kwargs):
    if <some condition>:
        raise SomeException('your message here')

You can find the available exceptions fpr django here: https://docs.djangoproject.com/en/1.3/ref/exceptions/ ,plus you can also use the standard python exceptions, for which you can find documentation here: http://docs.python.org/library/exceptions.html

I would recommend you to find an Exception that describes your problem, or you will be pretty confused if that error shows up in a few weeks, when you cannot remember what exactly you have been doing now.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-08-05 07:54

Pastylegs is correct, but you shouldn't be doing that sort of logic in the save method. Django has a built-in system for validating model instances before saving - you should use this, and raise ValidationError where necessary.

查看更多
登录 后发表回答