Django 继承一个类,但只使用必需的字段,而不是所有继承的字段

Django 继承一个类,但只使用必需的字段,而不是所有继承的字段,django,django-rest-framework,Django,Django Rest Framework,假设总共有3节课A、B和C class A(models.Model): one = models.IntegerField() two = models.IntegerField() three = models.IntegerField() class Meta: abstract = True class B(A): pass class C(A): pass 我继承了B和C中的类A,但我只想在类B中使用一个和两个,而

假设总共有3节课ABC

class A(models.Model):
    one = models.IntegerField()
    two = models.IntegerField()
    three = models.IntegerField()

    class Meta:
        abstract = True

class B(A):
    pass 

class C(A):
   pass
我继承了BC中的类A,但我只想在类B中使用一个两个,而类C中的所有三个字段

class A(models.Model):
    one = models.IntegerField()
    two = models.IntegerField()
    three = models.IntegerField()

    class Meta:
        abstract = True

class B(A):
    pass 

class C(A):
   pass
是否可以继承classBclassA的一些字段和classC中的一些字段


或者这是一个坏主意?

正如您可能已经知道的,有三种类型

  • 通常,您只需要使用父类来保存不需要为每个子模型键入的信息。这个类永远不会单独使用,所以抽象基类是您所追求的
  • 如果您正在对现有模型(可能完全来自另一个应用程序)进行子类化,并且希望每个模型都有自己的数据库表,那么多表继承就是一种方法
  • 最后,如果只想修改模型的Python级行为,而不以任何方式更改模型字段,那么可以使用代理模型
  • 用例的唯一选择是
    抽象基类

    你要找的是:

    从抽象基类继承的字段可以用另一个字段或值覆盖,也可以不用任何字段或值删除

    因此,你应该:

    class A(models.Model):
        one = models.IntegerField()
        two = models.IntegerField()
        three = models.IntegerField()
    
        class Meta:
            abstract = True
    
    
    class B(A):
        three = None
    
    
    class C(A):
        three = None
    
    回答你的第二个问题,这不是一个坏主意;在扩展django的默认用户模型时,我们通常在想要更改
    USERNAME\u字段时使用它