I\'ve got a Django class like this:
class Breakfast(m.Model):
# egg = m.OneToOneField(Egg)
...
class Egg(m.Model):
breakfast = m.OneToOneField(Break
I would recommend using try
/ except Egg.DoesNotExist
whenever you need to access Breakfast.egg
; doing so makes it very clear what's going on for people reading your code, and this is the canonical way of handling nonexistent records in Django.
If you really want to avoid cluttering your code with try
/ except
s, you could define a get_egg
method on Breakfast
like so:
def get_egg(self):
""" Fetches the egg associated with this `Breakfast`.
Returns `None` if no egg is found.
"""
try:
return self.egg
except Egg.DoesNotExist:
return None
This will make it clearer to people reading your code that eggs are derived, and it may hint at the fact that a lookup gets performed when one calls Breakfast.get_egg()
.
Personally, I'd go for the former approach in order to keep things as clear as possible, but I could see why one may be inclined to use the latter approach instead.