I have a method that must return one of three objects depending on their existence.
My implementation
try:
return Model.objects.get(param=param)
except Model.DoesNotExist as ex:
# go to the next verification
pass
try:
return RelatedModel.objects.get(param=param).model
except RelatedMolel.DoesNotExist as ex:
# get the default model
pass
return Model.objects.get_default()
So question for the guru of python - is it a more pythonic implementation than inner try/catch blocks or ?
try:
return Model.objects.get(param=param)
except Model.DoesNotExist as ex:
try:
return RelatedModel.objects.get(param=param).model
except RelatedModel.DoesNotExist as ex:
return Model.objects.get_default()
From the Zen of Python (import this
):
Flat is better than nested.
I would prefer the first version in this case.
The docs tell us:
ObjectDoesNotExist
is defined indjango.core.exceptions
.DoesNotExist
is a subclass of the baseObjectDoesNotExist
exception that is provided on every model class as a way of identifying the specific type of object that could not be found.
So what I'd do is:
queries = [lambda: Model.objects.get(param=param),
lambda: RelatedModel.objects.get(param=param).model,
lambda: Model.objects.get_default()]
for query in queries:
try:
return query()
except ObjectDoesNotExist:
pass
Arguably this way isn't "obvious", but it's both flat, reduces redundancy, and keeps related things together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With