Opened 14 years ago
Closed 14 years ago
#17546 closed New feature (duplicate)
Add QuerySet.get_or_none(why='brevity')
| Reported by: | Vlada Macek | Owned by: | nobody |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | yes | UI/UX: | no |
Description
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. :)
Closing as a duplicate of #2659 and #11352, both of which were wontfixed.