【问题标题】:Checking if objects exists and manually raising an error if it doesn't检查对象是否存在,如果不存在则手动引发错误
【发布时间】:2019-11-12 10:41:53
【问题描述】:

我需要检查表中是否存在对象,如果没有引发错误并将其自动保存到 django cronjoblog 表中。

这是一个部分执行我想要的代码,但它不会引发错误并将其保存到 cronjoblog 表中:

from django.core.exceptions import ObjectDoesNotExist

some_object= Some_object.objects.filter(active=True)
try:
    some_object.get()
except ObjectDoesNotExist:
    print("Either the entry or blog doesn't exist.")

我需要类似的东西:

some_object= Some_object.objects.filter(active=True)
if not some_object:
    raise ObjectDoesNotExist("Either the entry or blog doesn't exist.")

【问题讨论】:

    标签: python django error-handling


    【解决方案1】:

    您可以如下修改现有代码。

    try:
        some_object.get()
    except ObjectDoesNotExist as e:
        raise ObjectDoesNotExist("Either the entry or blog doesn't exist.") from e
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-26
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 2011-05-12
      相关资源
      最近更新 更多