django - 基于对象状态的自定义错误消息
问题描述
例如,我有一个具有多种状态的模型。
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 视图干净的最佳方法是什么?
解决方案
我喜欢分享我的想法,这可能是您问题的解决方案。
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
是一种不好的做法。
推荐阅读
- visual-studio-code - 在 VSCode 扩展中使用 Azure Ad 进行身份验证
- c# - 具有天蓝色功能的普罗米修斯
- javascript - > 任务:app:processDebugMainManifest 失败
- google-sheets - 如何替换一个谷歌表格列的值并自动导入另一列的值?
- visual-studio-code - Visual Studio Code 询问您是否信任此工作区的作者是否正常?
- python - 每次我必须进行预测时,我都必须以保存的模型格式加载 tensorlflow 模型。如果适应视频源,我该如何适应?
- python - 在 yolov3 模型上进行多批次推理时出错
- python - 为什么 Android Gmail 应用程序中的内嵌图片也会显示为附件?
- node.js - Mongoose $aggregation 和 $lookup 直到同一个集合中的第 n 个孩子用于父子关系
- text - 将行 x 替换为行 y