How do I get the object if it exists, or None if it does not exist?

后端 未结 19 1604
清酒与你
清酒与你 2020-11-28 01:14

When I ask the model manager to get an object, it raises DoesNotExist when there is no matching object.

go = Content.objects.get(name=\"baby\")
         


        
19条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 01:42

    We can use Django builtin exception which attached to the models named as .DoesNotExist. So, we don't have to import ObjectDoesNotExist exception.

    Instead doing:

    from django.core.exceptions import ObjectDoesNotExist
    
    try:
        content = Content.objects.get(name="baby")
    except ObjectDoesNotExist:
        content = None
    

    We can do this:

    try:
        content = Content.objects.get(name="baby")
    except Content.DoesNotExist:
        content = None
    

提交回复
热议问题