Django objects.get ()

What if nothing works? Then he returns with an error.

How can I say: receive, if any, otherwise return nothing.

+3
source share
3 answers

You can 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

I don’t know why this shortcut does not exist (maybe someone with a lot of django under their waist can explain), because this is a reasonably useful shortcut that I use from time to time.

+7
source

Use try/exceptorget_object_or_404

+3
source

or you can try django annoy

pip install django-annoying

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

from annoying.functions import get_object_or_None
get_object_or_None(User, email='test@test.com')

Here is the repo on github project

+2
source

Source: https://habr.com/ru/post/1737956/


All Articles