Django Abstract base classes and Meta inheritance(Django抽象基类以及元继承)

30 篇文章 0 订阅

Django Abstract base classes

Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.

当我们需要将一些公用信息在其他一些模型中使用的时候,抽象基类就显得非常实用。我们定义一个基类然后在元类中设置abstract=True,那么这个模型将不会被用来创建数据表。而且,当它作为一个基类被继承的时候,它的字段将被加到子类中去。

示例如下:

from django.db import models

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

    class Meta: ### Here 
        abstract = True ### Here 

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

重点:抽象基类不会生成对应的数据表,不能被实例化和保存

Meta inheritance

When an abstract base class is created, Django makes any Meta inner class you declared in the base class available as an attribute. If a child class does not declare its own Meta class, it will inherit the parent’s Meta. If the child wants to extend the parent’s Meta class, it can subclass it. For example:

当一个抽象基类被创建的时候,Django 将会使基类的元类属性被继承。如果一个子类没有声明自己的元类,那么它将继承父类的元类。如果一个子类想要拓展父类的元类,那么他可以定义自己的元类。

from django.db import models

class CommonInfo(models.Model):
    # ...
    class Meta:
        abstract = True
        ordering = ['name']

class Student(CommonInfo):
    # ...
    class Meta(CommonInfo.Meta):
        db_table = 'student_info'

Django does make one adjustment to the Meta class of an abstract base class: before installing the Meta attribute, it sets abstract=False. This means that children of abstract base classes don’t automatically become abstract classes themselves. Of course, you can make an abstract base class that inherits from another abstract base class. You just need to remember to explicitly set abstract=True each time.

对于抽象类的继承,在安装元类属性前子类会先设置abstract=False属性,这就意味着子类不会自动成为抽象类。当然抽象类可以多次继承,只不过每次继承时都必须要设置abstract=True属性。

Some attributes won’t make sense to include in the Meta class of an abstract base class. For example, including db_table would mean that all the child classes (the ones that don’t specify their own Meta) would use the same database table, which is almost certainly not what you want.

有些元类属性就算设置了也米有任何意义。例如:db_table 属性的定义意味着所有的子类都将生成一张同名表,当然这不是我们想要的。

本文官网链接:https://docs.djangoproject.com/en/2.0/topics/db/models/#abstract-base-classes

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值