When I ask the model manager to get an object, it raises DoesNotExist
when there is no matching object.
go = Content.objects.get(name=\"baby\")
I think it isn't bad idea to use get_object_or_404()
from django.shortcuts import get_object_or_404
def my_view(request):
my_object = get_object_or_404(MyModel, pk=1)
This example is equivalent to:
from django.http import Http404
def my_view(request):
try:
my_object = MyModel.objects.get(pk=1)
except MyModel.DoesNotExist:
raise Http404("No MyModel matches the given query.")
You can read more about get_object_or_404() in django online documentation.
Here's a variation on the helper function that allows you to optionally pass in a QuerySet
instance, in case you want to get the unique object (if present) from a queryset other than the model's all
objects queryset (e.g. from a subset of child items belonging to a parent instance):
def get_unique_or_none(model, queryset=None, **kwargs):
"""
Performs the query on the specified `queryset`
(defaulting to the `all` queryset of the `model`'s default manager)
and returns the unique object matching the given
keyword arguments. Returns `None` if no match is found.
Throws a `model.MultipleObjectsReturned` exception
if more than one match is found.
"""
if queryset is None:
queryset = model.objects.all()
try:
return queryset.get(**kwargs)
except model.DoesNotExist:
return None
This can be used in two ways, e.g.:
obj = get_unique_or_none(Model, **kwargs)
as previosuly discussedobj = get_unique_or_none(Model, parent.children, **kwargs)
You can create a generic function for this.
def get_or_none(classmodel, **kwargs):
try:
return classmodel.objects.get(**kwargs)
except classmodel.DoesNotExist:
return None
Use this like below:
go = get_or_none(Content,name="baby")
go
will be None
if no entry matches else will return the Content entry.
Note:It will raises exception MultipleObjectsReturned
if more than one entry returned for name="baby"
.
You should handle it on the data model to avoid this kind of error but you may prefer to log it at run time like this:
def get_or_none(classmodel, **kwargs):
try:
return classmodel.objects.get(**kwargs)
except classmodel.MultipleObjectsReturned as e:
print('ERR====>', e)
except classmodel.DoesNotExist:
return None
From django docs
get()
raises aDoesNotExist
exception if an object is not found for the given parameters. This exception is also an attribute of the model class. TheDoesNotExist
exception inherits fromdjango.core.exceptions.ObjectDoesNotExist
You can catch the exception and assign None
to go.
from django.core.exceptions import ObjectDoesNotExist
try:
go = Content.objects.get(name="baby")
except ObjectDoesNotExist:
go = None
We can use Django builtin exception which attached to the models named as .DoesNotExist
. So, we don't have to import ObjectDoesNotExist
exception.
Instead doing:
from django.core.exceptions import ObjectDoesNotExist
try:
content = Content.objects.get(name="baby")
except ObjectDoesNotExist:
content = None
We can do this:
try:
content = Content.objects.get(name="baby")
except Content.DoesNotExist:
content = None
You can do it this way:
go = Content.objects.filter(name="baby").first()
Now go variable could be either the object you want or None
Ref: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.first