我在应用程序中遇到了一个DoesNotExist
错误。问题是我并不真正理解为什么会抛出这个错误,因为我已经处理过了:
import socket
from django.core.exceptions import ObjectDoesNotExist
from django.db import Models
class MyClass(models.Model):
name = models.CharField(max_length=250, default=socket.gethostname(), unique=True)
@staticmethod
def update_some_list(some_list):
for some_item in some_list:
try:
MyClass.objects.get(name=some_item)
except ObjectDoesNotExist: # I also tried with MyClass.DoesNotExist
MyClass.objects.create(name=some_item)
这里要说的是,当我遇到这段代码时,我会遇到一些被丢弃的“模块级别”的DoesNotExist异常,就好像这个try/except块从未被触发过。
Traceback (most recent call last):
File "/app/backend/shared/models.py", line 201, in update_some_list
MyClass.objects.get(name=some_item)
File "/usr/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
shared.models.DoesNotExist: MyClass matching query does not exist.
shared.models
中的异常? - Willem Van Onsemprint(type(e).__qualname__)
。 - Willem Van Onsemdjango.core.exceptions.ObjectDoesNotExist
,但实际上抛出的是shared.models.DoesNotExist
。 - Tryph@staticmethod
有关?无论如何,我重新部署了一个新的调试版本,其中包含了你们两个提议的混合体,catch Error as e
和print(type(e).__qualname__)
都没有输出任何内容。 - Yoiro