Opened 8 years ago

Closed 8 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: master
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


I frequently write this as recommended:

    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):
        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. :)

Change History (1)

comment:1 Changed 8 years ago by Russell Keith-Magee

Resolution: duplicate
Status: newclosed

Closing as a duplicate of #2659 and #11352, both of which were wontfixed.

Note: See TracTickets for help on using tickets.
Back to Top