首页 > 解决方案 > 基于对象状态的自定义错误消息

问题描述

例如,我有一个具有多种状态的模型。

class Task(models.Model):
    TO_DO = 'to_do'
    IN_PROGRESS = 'in_progress'
    DONE = 'done'
    TASK_STATUSES = (
        (TO_DO, _('To do')),
        ...
    )
    status = models.CharField(max_length=256, choices=TASK_STATUSES)
    creator = models.ForeignKey('user.User', on_delete=models.CASCADE)

    def is_to_do(self):
        return self.status == self.TO_DO

    def is_in_progress(self):
        return self.status == self.IN_PROGRESS

     def is_done(self):
        return self.status == self.DONE

而且我有端点,我想对我的任务执行操作。在此之前,我想检查是否允许根据对象状态和其他内容执行此操作。我可能有几个if statements喜欢:

obj = get_object()
if object.is_in_progress() and object.creator.name = '...':
    raise NotAcceptable(detail=_('...'))
if ...
...
else: 
    obj.update_status()

每个异常都可能有它自己的错误消息。我可以将这些消息存储在模型上,但我仍然有很多if只引发异常。那么执行此类检查并保持我的 api 视图干净的最佳方法是什么?

标签: djangodjango-rest-framework

解决方案


我喜欢分享我的想法,这可能是您问题的解决方案。

status_message = None
error_type = None
try:
    # update/implement what you want
    print(1/0)
except Exception as ex:
    status_message = ex
    error_type = ex.__class__.__name__
    # get the status model by your exception
    model_obj = your_model.objects.get(error_type=error_type)
    if model_obj == None or model_obj.id == None:
        # if status model has not entry than created new one and than response.
        your_model.save(status_message=status_message, error_type=error_type)
        raise Response(your_model.__dict__) # you may serialize your response
    raise Response(model_obj.__dict__)

注意:在博客中编写代码except是一种不好的做法。


推荐阅读