Re:Python 3.11: “Zero cost” exception handling
by _bohm on Wednesday October 06, 2021 @09:55AM
(#28773236)
This fails to raise an error if there is more than one object matching the given filters
[ Parent
| on HN ]
Re:Python 3.11: “Zero cost” exception handling
by notdonspaulding on Wednesday October 06, 2021 @12:28PM
(#28775021)
Presumably entry_number is unique_together with blog_id. Otherwise the original code is also not handling the MultipleObjectsReturned exception.
Generally speaking, I tend toward the cleanest code being:
blog = Blog.objects.get(id=1)
entry = blog.entry_set.filter(entry_number=1).first()
if entry is None:
handle_missing_entry()
handle_entry(entry)
But it does suffer from having the extra DB query in there, which may or may not be helpful, depending on the surrounding code (and whether or not you'll be using the blog instance anywhere else).