Django:如何创建自定义" base"模型

时间:2015-07-27 07:42:23

标签: python django django-models

在我的几乎所有表格中(= models.Model的类)我有三个DateTimeField

  • 创建
  • 有效性开始
  • validity end

有没有办法建立一个"基地"我声明那些字段的模型类,并使我所有的其他模型扩展这个字段?我无法在网上找到有价值的答案。

2 个答案:

答案 0 :(得分:18)

您需要创建一个包含这些公共字段的抽象基类,然后在模型中继承此基类。

第1步:创建Abstract Base Class

我们首先创建一个名为BaseModel的抽象基类。此BaseModel类包含3个模型字段creation_datevalididity_start_datevalidity_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
    ...

此处,MyModel1MyModel2类包含来自基类creation_date的3个字段valididity_start_datevalidity_end_dateBaseModel其中定义的其他模型字段。

答案 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扩展到其他模型类