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

Oli*_*ons 12 python django django-models

几乎所有的表(=类models.Model)都有三个DateTimeField:

  • 创建
  • 有效期开始
  • 有效期结束

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

Rah*_*pta 21

您需要创建具有这些公共字段的抽象基类,然后在模型中继承此基类.

步骤1:创建抽象基类

我们首先创建一个名为的抽象基类BaseModel.这个BaseModel类包含3分示范田creation_date,valididity_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
Run Code Online (Sandbox Code Playgroud)

步骤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
    ...
Run Code Online (Sandbox Code Playgroud)

这里,类包含3个字段,并且除了在其中定义的其他模型字段之外,MyModel1MyModel2包含基类.creation_datevalididity_start_datevalidity_end_dateBaseModel


Geo*_*cob 8

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
Run Code Online (Sandbox Code Playgroud)

这样你就可以定义你的模型并将 Basetable 扩展到其他模型类