|Reported by:||Tuttle||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||master|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I frequently write this as recommended:
try: obj = MyModel.objects.get(...) except MyModel.DoesNotExist: obj = None
It's wordy, reading try...except is a bit disturbing, especially in case None is a valid value for that codepath.
I guess, something like this could be added right away to the QuerySet class:
def get_or_none(self, *args, **kwargs): try: return self.model.objects.get(*args, **kwargs) except model.DoesNotExist: return None
#5741 suggested a default= kwargs for get(), but I dislike tainting the kwargs (possible collisions, overloading).
Sure I can create my own shortcut similar to get_object_or_404(model, ...), but I think having get_or_none() directly in a QuerySet would be very intuitive and broadly helpful.
It sure would be for me. :)