Created
October 19, 2009 11:20
-
-
Save maxp/213294 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_object_or_none(klass, *args, **kwargs): | |
if isinstance(klass, Manager): | |
manager = klass | |
klass = manager.model | |
else: | |
manager = klass._default_manager | |
try: | |
return manager.get(*args, **kwargs) | |
except klass.DoesNotExist: | |
return None | |
def get_object_or_none(klass, *args, **kwargs): | |
""" | |
Uses get() to return an object or None if the object does not exist. | |
klass may be a Model, Manager, or QuerySet object. All other passed | |
arguments and keyword arguments are used in the get() query. | |
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one | |
object is found. | |
""" | |
queryset = _get_queryset(klass) | |
try: | |
return queryset.get(*args, **kwargs) | |
except queryset.model.DoesNotExist: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment