问题
I am learning to use the ContentType framework and need some help raising an exception for 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.
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
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?
回答1:
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
来源:https://stackoverflow.com/questions/33988910/django-proper-exception-for-contenttype-get-object-for-this-type