Search code examples
pythondjangodjango-queryset

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


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")

Instead of DoesNotExist, how can I have go be None instead?


Solution

  • There is no 'built in' way to do this as of version 1.2. Django will raise the DoesNotExist exception every time.

    The idiomatic way to handle this in Python is to wrap it in a try catch:

    try:
        go = SomeModel.objects.get(foo='bar')
    except SomeModel.DoesNotExist:
        go = None
    

    What I did was to subclass models.Manager, create a safe_get like the code above, and use that manager for my models. That way you can write one line to achieve this:

    SomeModel.objects.safe_get(foo='bar')