在我的几乎所有表格中(= models.Model
的类)我有三个DateTimeField
:
有没有办法建立一个"基地"我声明那些字段的模型类,并使我所有的其他模型扩展这个字段?我无法在网上找到有价值的答案。
答案 0 :(得分:18)
您需要创建一个包含这些公共字段的抽象基类,然后在模型中继承此基类。
第1步:创建Abstract Base Class
我们首先创建一个名为BaseModel
的抽象基类。此BaseModel
类包含3个模型字段creation_date
,valididity_start_date
和validity_end_date
,这些字段在您的几乎所有模型中都很常见。
在内部Meta
课程中,我们设置abstract=True
。然后,此模型不会用于创建任何数据库表。相反,当它用作其他模型的基类时,其字段将添加到子类的字段中。
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
步骤2:在模型中继承此Base类
在创建抽象基类BaseModel
之后,我们需要在模型中继承此类。这可以使用Python中的普通继承来完成。
class MyModel1(BaseModel): # inherit the base model class
# define other non-common fields here
...
class MyModel2(BaseModel): # inherit the base model class
# define other non-common fields here
...
此处,MyModel1
和MyModel2
类包含来自基类creation_date
的3个字段valididity_start_date
,validity_end_date
和BaseModel
其中定义的其他模型字段。
答案 1 :(得分:4)
class Basetable(models.Model):
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.DateTimeField(auto_now=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_createdby')
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='%(class)s_modifiedby', null=True, blank=True)
class Meta:
abstract = True
通过这种方式,您可以定义模型并将Basetable扩展到其他模型类