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

后端 未结 6 1415
失恋的感觉
失恋的感觉 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条回答
  •  旧时难觅i
    2021-02-04 02:28

    I just ran into this problem, and found an odd solution to it: if you select_related(), then the attribute will be None if no related row exists, instead of raising an error.

    >>> print Breakfast.objects.get(pk=1).egg
    Traceback (most recent call last):
    ...
    DoesNotExist: Egg matching query does not exist
    
    >>> print Breakfast.objects.select_related("egg").get(pk=1).egg
    None
    

    I have no idea if this can be considered a stable feature though.

提交回复
热议问题