Code

Opened 2 years ago

Closed 2 years ago

#17546 closed New feature (duplicate)

Add QuerySet.get_or_none(why='brevity')

Reported by: Tuttle 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

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

Attachments (0)

Change History (1)

comment:1 Changed 2 years ago by russellm

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to duplicate
  • Status changed from new to closed

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

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.