Django-ContentType.get_object_for_this_type()的适当异常 [英] Django - Proper exception for ContentType.get_object_for_this_type()
问题描述
我正在学习使用 ContentType框架,并且需要一些帮助来引发 get_object_for_this_type()
的异常。
I am learning to use the ContentType framework and need some help raising an exception for get_object_for_this_type()
.
根据代码:
为给定的关键字参数返回此类型的对象。
基本上,这是围绕此object_type的get_object()模型
方法的代理。如果抛出ObjectNotExist异常,则不会捕获
,因此调用此方法的代码应捕获该异常。
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.
I我想知道是否有办法在不引入被引用的实际模型的情况下做到这一点。例如,如果我想执行以下操作:
I am wondering if there is a way to do this without bringing in the actual models being referenced. For example if I wanted to do something like this:
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'对象没有属性'DoesNotExist'
。是否可以在不指定模型中所有模型的情况下执行此操作?
This exception informs me that 'ContentTypeManager' object has no attribute 'DoesNotExist'
. Is there a way to do this without specifying all of the models in models?
推荐答案
在其他文档部分找到了此方法,不要问我在哪里。在这种情况下使用的适当例外是 django.core.excpetions.ObjectDoesnotExist
Found this on some other part of the docs, don't ask me where. The proper exception to be used in this situation is 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
这篇关于Django-ContentType.get_object_for_this_type()的适当异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!