例如,我有一个带有几种状态的模型。
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视图干净的最佳方法是什么?
答案 0 :(得分:0)
我想分享一下我的想法,这也许可以解决您的问题。
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
博客中编写代码是一种不良做法。