Is there any Django function which will let me get an object form the database, or None if nothing matches?
Right now I\'m using something like:
foo
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, *args, **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(*args, **kwargs)
except model.DoesNotExist:
return None
This can be used in two ways, e.g.:
obj = get_unique_or_none(Model, *args, **kwargs)
as previosuly discussedobj = get_unique_or_none(Model, parent.children, *args, **kwargs)