Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django objects.get()

Tags:

python

django

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.

like image 243
TIMEX Avatar asked Jul 26 '26 00:07

TIMEX


1 Answers

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.

like image 113
Rory Hart Avatar answered Jul 27 '26 16:07

Rory Hart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!