Created
July 23, 2018 14:25
-
-
Save jsatt/846dd170bb66a50728308c8003a62962 to your computer and use it in GitHub Desktop.
django get_or_none
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
from django.db.models import Model, Manager, QuerySet | |
def get_or_none(model, *args, **kwargs): | |
if issubclass(model, Model): | |
qs = model._default_manager.all() | |
elif isinstance(model, Manager): | |
qs = model.all() | |
manager = model | |
model = manager.model | |
elif isinstance(model, QuerySet): | |
qs = model | |
model = qs.model | |
else: | |
raise Exception(f'You must provide a Model, Manager or QuerySet instance.') | |
try: | |
return qs.get(*args, **kwargs) | |
except model.DoesNotExist: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment