7π
β
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.
π€Rory Hart
- [Django]-Django Test β South migration reports 'no such table' but I can see said table in the db
- [Django]-Django 1.9: Should I avoid importing models during `django.setup()`?
- [Django]-Django 1.6 + RabbitMQ 3.2.3 + Celery 3.1.9 β why does my celery worker die with: WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV)
- [Django]-How to return all records but exclude the last item
- [Django]-Django giving error ImportError: No module named 'corsheaders'
2π
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='test@test.com')
Here is the project repo on github
π€llazzaro
Source:stackexchange.com