1、使用最原始的方式继承
class Animal(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() class Cat(Animal): weight = models.IntegerField() class Dog(Animal): height = models.IntegerField()
注意:继承方式不是很合理,父类也会对应一张表。 效率比较低。
默认在父类中定义的字段会存在父类表中,子类的数据通过外键关联父表中数据,子类只有特殊的数据在子表中。
2、Django中的数据库模块提供了一个非常不错的功能,就是支持models的面向对象,可以在Meta类中指定是否抽象,然后继承。
class Animal(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() class Meta(): # 让该类抽象,抽象的父类不会再生产数据表 # 子类会继承父类中的通用数据,复制到子表中 abstract = True class Cat(Animal): weight = models.IntegerField() class Dog(Animal): height = models.IntegerField()