您的问题表明您希望构建一个抽象类以用作模型继承的基类。这里有一些非常棒的文档。
例如:
class CommonInfo(models.Model):
notes = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(blank=True, default=datetime.datetime.now)
last_modified_at = models.DateTimeField(blank=True, default=datetime.datetime.now)
class Meta:
abstract = True # This line is what makes the class an abstract class
def we_all_do_this(self):
pass
def we_all_do_this_too(self):
pass
class ChildA(CommonInfo): # Note that ChildA class inherits from the CommonInfo abstract base class
name = models.CharField(blank=True, null=True, max_length=100)
state = models.CharField(blank=True, null=True, max_length=100)
def only_i_do_this(self):
pass
class ChildB(CommonInfo): # Note that ChildB class inherits from the CommonInfo abstract base class
title = models.CharField(blank=True, null=True, max_length=100)
date = models.DateField(default=datetime.datetime.today)
def only_i_do_this(self):
pass