0

When I do a lookup in dictionaries, I frequently use dict.get() so that it won't raise an exception if the key is missing. Even better, I can specify a default value when the key doesn't exist.

Is there an equivalent for Django querysets? It seems like the best I can do is this--

try:
    author = Book.objects.get(title='Hamlet').author
except Book.DoesNotExist:
    author = None

Makes sense, but I'm wondering if there is a more elegant way.

nofinator
  • 2,906
  • 21
  • 25

1 Answers1

0
books = Book.objects.filter(title='Hamlet')[:1]  # LIMIT 1
book = books[0] if books else None

This should be the most optimal way of achieving what you need.

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
  • I don't think it's a good way to code this.. – 9Algorithm Sep 27 '13 at 13:44
  • You're free to propose a better solution—I have nothing against somebody finding an improved way of doing something compared to what I came up with. Anyway, I'd normally just catch `DoesNotExist` and assign `book` to `None` but he explicitly stated he doesn't like that. – Erik Kaplun Sep 27 '13 at 22:13