Model.objects.get () or None

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

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

The only way I found a way to do this is to do:

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

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

Refresh . It doesn't seem like it is like in a block try/except, but here is the best answer: In Django, how do I object.get, but return None when nothing is found?

+5
source share
3 answers

How about this:

obj = Model.objects.filter(id=1).first()

now, if there is no object with id = 1 obj, it will be None

Link: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.first

+13
source

- 404, , ,

get_object_or_404(Mode, pk=1)
+2

get_object_or_404

in your model.,.

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

All Articles