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

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

    Without exception:

    if SomeModel.objects.filter(foo='bar').exists():
        x = SomeModel.objects.get(foo='bar')
    else:
        x = None
    

    Using an exception:

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

    There is a bit of an argument about when one should use an exception in python. On the one hand, "it is easier to ask for forgiveness than for permission". While I agree with this, I believe that an exception should remain, well, the exception, and the "ideal case" should run without hitting one.

提交回复
热议问题