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

后端 未结 19 1599
清酒与你
清酒与你 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

    From django docs

    get() raises a DoesNotExist exception if an object is not found for the given parameters. This exception is also an attribute of the model class. The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist

    You can catch the exception and assign None to go.

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

提交回复
热议问题