Django - ContentType.get_object_for_this_type() 的正确异常

Django - Proper exception for ContentType.get_object_for_this_type()

我正在学习使用 ContentType framework 并需要一些帮助引发 get_object_for_this_type() 的异常。

According to the code:

Returns an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type's get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it.

我想知道是否有一种方法可以在不引入所引用的实际模型的情况下执行此操作。例如,如果我想做这样的事情:

for model in models
    try:
        i = ContentType.objects.get(app_label="Users", model=model)
        obj = i.get_object_for_this_type(user=self)
        self.profile_type = obj
        self.save()
    except ContentType.object.DoesNotExist:
        continue

这个异常告诉我'ContentTypeManager' object has no attribute 'DoesNotExist'。有没有办法在不指定模型中的所有模型的情况下执行此操作?

在文档的其他部分找到这个,不要问我在哪里。在这种情况下使用的正确例外是 django.core.excpetions.ObjectDoesnotExist

from django.core.exceptions import ObjectDoesNotExist

for model in models:
    try:
        i = ContentType.objects.get(app_label="Users", model=model)
        obj = i.get_object_for_this_type(user=self)
        self.slug = obj.slug
        self.save()
        return self.profile_type
    except ObjectDoesNotExist:
        continue