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

后端 未结 6 1406
失恋的感觉
失恋的感觉 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:13

    OmerGertel did already point out the null option. However, if I understand your logical model right, then what you actually need is a unique and nullable foreign key from Breakfast to Egg. So a breakfast may or may not have an egg, and a particular egg can only be associated with one breakfast.

    I used this model:

    class Egg(models.Model):
        quality = models.CharField(max_length=50)
        def __unicode__(self):
            return self.quality
    
    class Breakfast(models.Model):
        dish = models.TextField()
        egg = models.ForeignKey(Egg, unique=True, null=True, blank=True)
        def __unicode__(self):
            return self.dish[:30]
    

    and this admin definition:

    class EggAdmin(admin.ModelAdmin):
        pass
    
    class BreakfastAdmin(admin.ModelAdmin):
        pass
    
    admin.site.register(Egg, EggAdmin)
    admin.site.register(Breakfast, BreakfastAdmin)
    

    Then I could create and assign an egg in the edit page for a breakfast, or just do not assign one. In the latter case, the egg property of the breakfast was None. A particular egg already assigned to some breakfast could not be selected for another one.

    EDIT:

    As OmerGertel already said in his comment, you could alternatively write this:

        egg = models.OneToOneField(Egg, null=True, blank=True)
    

提交回复
热议问题