Django: testing get query
Posted
by Brant
on Stack Overflow
See other posts from Stack Overflow
or by Brant
Published on 2010-03-26T16:43:44Z
Indexed on
2010/03/26
17:03 UTC
Read the original article
Hit count: 467
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?
© Stack Overflow or respective owner