class BaseModel(models.Model): # base class should subclass 'django.db.models.Model'
creation_date = models.DateTimeField(..) # define the common field1
validity_start_date = models.DateTimeField(..) # define the common field2
validity_end_date = models.DateTimeField(..) # define the common field3
class Meta:
abstract=True # Set this model as Abstract
这样您就可以定义模型并将Basetable扩展到其他模型类
您需要创建一个具有这些公共字段的抽象基类,然后在模型中继承这个基类。
第1步:创建Abstract Base Class
我们首先创建一个名为},它们几乎在你的每个模型中都很常见。在
BaseModel
的抽象基类。这个BaseModel
类包含3个模型字段creation_date
、valididity_start_date
和{在内部的
Meta
类中,我们设置abstract=True
。然后,此模型将不用于创建任何数据库表。相反,当它被用作其他模型的基类时,它的字段将被添加到子类的字段中。在第2步:在模型中继承这个基类
在创建抽象基类
^{pr2}$BaseModel
之后,我们需要在模型中继承这个类。这可以像在Python中那样使用普通继承来完成。在这里,}三个字段,而基类中定义的其他模型字段除外。在
MyModel1
和MyModel2
类包含基类creation_date
、valididity_start_date
和{相关问题 更多 >
编程相关推荐