'Model.objects.get() or None

Is there a way to accomplish the following in one call:

Model.objects.get(id=1) else None

The only way I've found a way to do this is by doing:

try:
    object = Model...
except:
    object = None

Is there a way to do this in a single call in django?

Update: There does not seem to be a way to do this other than in a try/except block, but here is a better answer: In Django, how do I objects.get, but return None when nothing is found?



Solution 1:[1]

if you are using it in a web request, and you want to return 404 if the object does not exist maybe you should use

get_object_or_404(Mode, pk=1)

Solution 2:[2]

How about this?

model_to_find = next(iter(Model.objects.filter(id=1)), None)

Solution 3:[3]

get_object_or_404

in your model do . . .

@models.permalink
def get_absolute_url(self):
    return "/blog/%s/" self.slug

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JoseP
Solution 2 allan
Solution 3 eusid