我的应用程序中有一个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)
这里的要点是,当我遇到这个代码时,我有一些“模块级”不被扔掉,好像这个尝试/排除块永远不会被击中:
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.
最佳答案
考虑使用QuerySet.get_or_create,这将消除上述问题。
MyClass.objects.get_or_create(name=some_item)
另外,请注意,如果您访问@staticmethod中的类,那么将其更新为@classmethod是有意义的。另外,在你的问题中:
from django.db import Models
而不是
从django.db导入模型
关于python - Django在DosNotExist上的try/except仍然会抛出它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52254747/