Django: Return 'None' from OneToOneField if related object doesn't exist?

后端 未结 6 1397
失恋的感觉
失恋的感觉 2021-02-04 01:48

I\'ve got a Django class like this:

class Breakfast(m.Model):
    # egg = m.OneToOneField(Egg)
    ...

class Egg(m.Model):
    breakfast = m.OneToOneField(Break         


        
6条回答
  •  被撕碎了的回忆
    2021-02-04 02:24

    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 / excepts, 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.

提交回复
热议问题