抽象基类

当你想将一些共有信息放进其他一些model的时候,抽象化类是十分有用的。

你编写完基类之后,在Meta类属性中设置 abstract=True,

这个模型就不会被用来创建任何数据表取而代之的是,当它被用来作为一个其他model的基类时,

它的字段将被加入那些子类中。

如果抽象基类和它的子类有相同的名字 

class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

    class Meta:
        abstract = True

class Student(CommonInfo):
    home_group = models.CharField(max_length=5)
	

1.
class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

    class Meta:
        abstract = True
		
node2:/exam/mysite#python manage.py makemigrations 
No changes detected
You have mail in /var/spool/mail/root
node2:/exam/mysite# python manage.py migrate 
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  No migrations to apply.
node2:/exam/mysite#

Student 模型将有三个项:name,age和home_group .CommonInfo模型无法像一般的Django模型一样使用,

因为它是一个抽象基类。它无法生成一张数据表或者拥有一个管理器,并且不能实例化或者直接存储。


许多应用场景下,这种类型的模型继承恰好是你想要的。
原文地址:https://www.cnblogs.com/hzcya1995/p/13349101.html