There are two ways to do this;
try:
foo = Foo.objects.get(bar=baz)
except model.DoesNotExist:
foo = None
Or you can use a wrapper:
def get_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except model.DoesNotExist:
return None
Call it like this
foo = get_or_none(Foo, baz=bar)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…