TIMEX
TIMEX

Reputation: 272432

Django objects.get()

What if there is nothing that matches the get? Then it returns in an error.

How do I say: get if there is, otherwise, return nothing.

Upvotes: 3

Views: 7028

Answers (3)

llazzaro
llazzaro

Reputation: 4188

or you can try django annoying

pip install django-annoying

then import get_object_or_None(klass, *args, **kwargs)

from annoying.functions import get_object_or_None
get_object_or_None(User, email='[email protected]')

Here is the project repo on github

Upvotes: 2

Rory Hart
Rory Hart

Reputation: 1893

You could create a shortcut like this (based on get_object_or_404):

from django.shortcuts import _get_queryset

def get_object_or_none(klass, *args, **kwargs):
  queryset = _get_queryset(klass)
  try:
    return queryset.get(*args, **kwargs)
  except queryset.model.DoesNotExist:
    return None

Not sure why this shortcut doesn't exist (perhaps someone with more django under their belt can explain) as it is a reasonably useful shortcut that I use from time to time.

Upvotes: 7

mpen
mpen

Reputation: 283355

Use try/except or get_object_or_404

Upvotes: 3

Related Questions