Okay, so I am sick of writing this…
res = Something.objects.filter(asdf=something)
if res:
single = res[0]
else:
single = None
if single:
# do some stuff
I would much rather be able to do something like this:
single = Something.objects.filter(asdf=something)
if single:
#do some stuff
I want to be able to grab a single object without testing the filtered results.
In other words, when i know there is either going to be 1 or 0 matching entries, I would like to jump right to that entry, otherwise just get a ‘None’. The DoesNotExist error that goes along with .get does not always work so well when trying to compress these queries into a single line.
Is there any way to do what I have described?
Create a custom
Managerwhich encapsulates the bit you’re sick of repeating as a method (with a better name than the one below) or just write a utility function which does the same without the hit to model definitions:Usage: