Opened 4 years ago

Closed 4 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


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 4 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.

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