Python 类继承和 Django 模型 ForeignKey 关系是两个完全不同的东西。听起来你指的是后者。
不同食物类型之间的字段是否如此不同,以至于您实际上需要为每种食物选择不同的模型?最简单的方法是为所有食物类型设置单一的食物模型。
class Food(models.model):
VEGETABLE = 'vegetable'
MEAT = 'meat'
FRUIT = 'fruit'
TYPE_CHOICES = [
(VEGETABLE, 'vegetable'),
(MEAT, 'meat'),
(FRUIT, 'fruit'),
]
type = models.CharField(max_length=10, choices=TYPE_CHOICES)
nutrition_content = models.OneToOneField('NutritionContent', on_delete=models.CASCADE)
# additional fields
class NutritionContent(models.Model):
# additional fields
如果您的字段在食物类型之间差异很大以至于您需要为每种食物类型设置不同的模型,您可以将 Food 设置为所有子食物类型模型与其具有 OneToOneField 关系的父模型。然后 NutritionContent 模型仍然可以与 Food 链接。
class Food(models.model):
nutrition_content = models.OneToOneField('NutritionContent', on_delete=models.CASCADE)
# fields that apply to all foods
class Vegetable(models.Model):
food = models.OneToOneField('Food', on_delete=models.CASCADE)
# additional fields that only apply to vegetables
class Meat(models.Model):
food = models.OneToOneField('Food', on_delete=models.CASCADE)
# additional fields that only apply to meat
class Fruit(models.Model):
food = models.OneToOneField('Food', on_delete=models.CASCADE)
# additional fields that only apply to fruit
class NutritionContent(models.Model):
# additional fields