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
Whether doing it via a manager or generic function, you may also want to catch 'MultipleObjectsReturned' in the TRY statement, as the get() function will raise this if your kwargs retrieve more than one object.
Building on the generic function:
def get_unique_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except (model.DoesNotExist, model.MultipleObjectsReturned), err:
return None
and in the manager:
class GetUniqueOrNoneManager(models.Manager):
"""Adds get_unique_or_none method to objects
"""
def get_unique_or_none(self, *args, **kwargs):
try:
return self.get(*args, **kwargs)
except (self.model.DoesNotExist, self.model.MultipleObjectsReturned), err:
return None