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

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

    There is no 'built in' way to do this. 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 do, is to subclass models.Manager, create a safe_get like the code above and use that manager for my models. That way you can write: SomeModel.objects.safe_get(foo='bar').

    0 讨论(0)
提交回复
热议问题