Search code examples
djangodjango-modelsnonetype

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

  • How about this:

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

    now if no object with id=1 exists obj would be None

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