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

后端 未结 6 1398
失恋的感觉
失恋的感觉 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 know that on ForeignKey you can have null=True when you want to allow the model not to point to any other model. OneToOne is only a special case of a ForeignKey:

    class Place(models.Model)
        address = models.CharField(max_length=80)
    class Shop(models.Model)
        place = models.OneToOneField(Place, null=True)
        name = models.CharField(max_length=50)
        website = models.URLField()
    
    >>>s1 = Shop.objects.create(name='Shop', website='shop.com')
    >>>print s1.place
    None
    

提交回复
热议问题