How to return an error message from the Model?

2019-08-05 07:40发布

问题:

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

回答1:

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.



回答2:

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.