我在自己的应用程序中遇到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)
这里的意思是,当我遇到这段代码时,我有一些“模块级” DosNotExist被扔掉了,好像这个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.
答案 0 :(得分:1)
考虑使用QuerySet.get_or_create,它将消除上述问题。
MyClass.objects.get_or_create(name=some_item)
还请注意,如果您在@staticmethod内部访问类,则将其更新为@classmethod是有意义的。另外,在您遇到的问题中:
from django.db import Models
而不是 从django.db导入模型