美文网首页
model inheritance

model inheritance

作者: xncode | 来源:发表于2017-09-13 17:01 被阅读0次

model的继承是和普通的python类继承相似的,只是最初的基类是应该从models.Model中派生出来

种类

1 如果父类的是子类的共有信息 同时该父类不会被直接使用的情况 可以使用abstract 这样就不会产生一个表 也没有manager 也不能直接被实例化

继承时如果想继承Meta则需要显示说明(默认情况:继承abstract model的新model是会自动变为非abstract的model,即会自动设置abstract=False)或是不定义自己的Meta则使用的是父类的Meta

2 直接继承model的情况(父类非abstract情况)

这样在子类的表中也有相应的字段 同时会自动产生一个 one to one字段连接到父类 (parent link = True),可以使用自定义的OneToOneField然后增加parent_link=True在这个字段上。

对于Meta还是不会继承 特殊情况,如果子类没有定义ordering、get_latest_by属性则会使用父类的值。

3 如果只是想在python层面上改变行为而不涉及model可以使用Proxy

这种情况下只是想改变一下manager或加一个新的方法

通过在Meta中定义proxy=True

或者设置不同的ordering即可获得不同排序效果的但是相同表的model

多继承

使用时以第一个出现的父类的字段为准

如果都有id字段会错误

一般的python中的继承,子类可以重载父类的属性,但是对于model则只能重载abstract model的字段。

相关文章

  • model inheritance

    model的继承是和普通的python类继承相似的,只是最初的基类是应该从models.Model中派生出来 种类...

  • Model inheritance 模型继承

    Django中模型的继承与Python普通类的继承一样,不过基类要是django.db.models.Model在...

  • Inheritance

    继承是swift中类区别于结构体和枚举等其他类型的主要原因。 子类可以调用或者重写父类的属性、方法和附属脚本。可以...

  • Inheritance

    Overriding Overriding Property Getters and Setters We can...

  • 1-多态

    1. 继承-inheritance 表达了实现的复用。inheritance 是从代码复用角度提出的概念,和类型没...

  • Swift - Inheritance

    Inheritance 类能添加属性观察者到继承属性中,无论是存储还是计算属性 某个类没有继承于其他类,就是基类 ...

  • Inheritance Note

    Hypernym and Hyponym We use the word hyponym for the oppo...

  • 52 - Inheritance

  • protected inheritance

    Accessibility of Derived-to-Base conversion in protected ...

  • django inheritance

    Abstract base classes 在元数据中设置Meta中设置 abstract=True ,这个mod...

网友评论

      本文标题:model inheritance

      本文链接:https://www.haomeiwen.com/subject/bgltcxtx.html