zoukankan      html  css  js  c++  java
  • Django继承

    Django目前支持两种不同的继承方式,包括抽象基础类和多表继承。

    1、抽象基础类:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    class Author(models.Model):
        name=models.CharField(max_length=20)
         
    class Book(models.Model):
        title=models.CharField(max_length=100)
        num_pages=models.IntegerField()
        authors=models.ManyToManyField(Author)
         
        def __str__(self):
            return self.title
         
        class Meta(object):
            abstract=True
             
     
    class SmithBook(Book):
        def __init__(self,*args,**kwargs):
            super(self,Book).__init__(*args,**kwargs)
            authors=models.ManyToManyField(Author,limit_choices_to={
                    "name_endswith":"Smith"
            })

     这里的关键是Meta嵌套类中的abstract=True,它指明了Book是一个基类。使用抽象基础类的方法,不会为基础类创建表。

    在子类中的嵌套类Meta会继承或是和基类中的Meta合并起来。

    attention:在SmithBook类中想要“重写”Book中的authors会出现错误,因为Django并不像python一样支持覆盖基类field的机制,但是我们可以通过在__init__方法中操作来达到同样的效果。

    2、多表继承:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Author(models.Model):
        name=models.CharField(max_length=20)
         
    class Book(models.Model):
        title=models.CharField(max_length=100)
        num_pages=models.IntegerField()
        authors=models.ManyToManyField(Author)
         
        def __str__(self):
            return self.title
             
     
    class SmithBook(Book):
        def __init__(self,*args,**kwargs):
            super(self,Book).__init__(*args,**kwargs)
            authors=models.ManyToManyField(Author,limit_choices_to={
                    "name_endswith":"Smith"
            })

     多表继承和抽象基础类从表面上来看,只是在Meta嵌套类中没有了abstract=True,但是在底层是有比较大的区别的。

    对于抽象基础类来说,Book是不能实例化的,而多表继承中的Book是可以实例化的。而且两者在数据库中创建的表也是不同的。

    参考博客https://www.cnblogs.com/lazyzhong/p/3490646.html

  • 相关阅读:
    Pandas数据结构简要概述
    pip install PyQt5和pip install PyQt5tools安装后,找不到designer.exe路径
    解决Qt5中利用designer建立二级菜单无法输入中文的处理技巧
    事务
    大家一起讨论一下朋友网的人脉关系算法是怎么实现的
    .net程序员必须学习的10项技术
    KENDOUI控件 GRID中TEMPLATE中条件判断的使用
    Kendo Template 模板中使用KendoUI组件
    Kendo.Grid 使用POPUP时分别定义Create和Edit模板
    Kendo UI 遮罩层组件
  • 原文地址:https://www.cnblogs.com/1204guo/p/8059344.html
Copyright © 2011-2022 走看看