Django模型管理器创建方法的验证异常
我正在使用一个自定义的Django模型管理器来创建一个实例。这个实例的字段是从一个指定的URL获取的数据生成的。其中一个字段是一个文件名,里面包含了我需要打开的JSON报告。我的问题是,如果我发现发生了错误(比如文件找不到,内容不合法等),在create()方法中抛出一个异常是否合理?有没有推荐的异常类型可以抛出?
这个模型需要解析后的数据才能创建一个有效的实例,所以在执行create()方法之前,我就已经知道这个模型是不合法的。
class IndexingUpdateRunManager(models.Manager):
def create_from_run(self,run_history_url):
run_info_dict = self.extract_fields_from_url(run_history_url)
run_config_file = run_info_dict["run_config_file"]
report_filename = run_info_dict["status_report_file"]
try:
out_fh = open(report_filename,'r')
report_data = json.loads(out_fh)
status_code=report_data["status"]
except Exception, e:
# throw an exception?
this_run=self.create(run_config_file_used=run_config_file,
report_filename = report_filename,
run_status_code=status_code)
return this_run
class MyUpdateRun(models.Model):
run_config_file_used = models.FilePathField(max_length=1024,
help_text="config file for run")
report_filename = models.FilePathField(max_length=1024,
help_text="status report file for run")
run_status_code = models.IntegerField(help_text="status code for overall run execution")
objects = MyUpdateRunManager()
>>MyUpdateRun.objects.create_from_run("https://server/job_status/builds/200/")
1 个回答
0
你可以抛出一个叫做 ObjectDoesNotExist 的错误,这个错误是来自 Django 框架的一个工具库。同时,你也可以自己创建一个新的错误类型,像这样:
class MyException(ObjectDoesNotExist):
pass
然后在一些特定的情况下,当 Django 提供的错误不够合适时,你就可以抛出这个错误。
补充一下:你的自定义错误也可以继承自基本的错误类型,像这样:
class MyException(Exception):
pass