Django - Proper exception for ContentType.get_object_for_this_type()

a 夏天 提交于 2020-01-06 21:58:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!