简体   繁体   English

Django每个模型必须有一个date_created和date_modified字段

[英]Django each model must have a date_created and date_modified field

Is there a way to have a date_created and date_modified fields for each and every model in models.py? 有没有办法为models.py中的每个模型都有一个date_createddate_modified字段?

I would like to have these two fields for each table being created so that I will be able to know when a row is created or updated. 我想为每个表创建这两个字段,以便我能够知道何时创建或更新行。

But I don't want to have them shown in my models.py specifically for each model. 但是我不希望在我的models.py中专门为每个模型显示它们。

Is there a way to do this? 有没有办法做到这一点?

You could for example define an abstract supermodel. 例如,您可以定义一个抽象超模。 Like: 喜欢:

class AppModel(models.Model):
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Here we use auto_now_add=True and auto_now , these parameters will even ensure that the date_created is automatically set to the timestamp when the object was created, and date_modified will automatically get updated when you update the object in the database. 这里我们使用auto_now_add=Trueauto_now ,这些参数甚至可以确保date_created自动设置为创建对象时的时间戳,并且date_modified将在您更新数据库中的对象时自动更新。

Then you can subclass it. 然后你可以继承它。 For example for a model called SomeModel : 例如,对于名为SomeModel的模型:

class SomeModel(AppModel):
    name = models.CharField(max_length=128)

Making the model abstract = True is rather important (well it can still work without making it abstract, but it will make the database quite messy and less efficient). 使模型abstract = True相当重要的(它仍然可以在不使其抽象的情况下工作,但它会使数据库变得非常混乱且效率较低)。 By specifying this is abstract, it will add the two columns to every model that inherits from this model. 通过指定这是抽象的,它将向从该模型继承的每个模型添加两列。 In case you do not make it abstract, Django will construct a new table, but typically this will make queries less efficient. 如果你没有将它抽象化,Django将构建一个新表,但通常这会使查询效率降低。

Since you here add columns to (potentially a large amount of) models, this will require a migration that will add the columns to the database level. 由于您在此处向(可能是大量)模型添加列,因此需要迁移以将列添加到数据库级别。 In case there is already data stored in the application, you will need to find a way to resolve the columns for rows that already exist (for example set it to NOW() , or to the beginning of times). 如果应用程序中已存储了数据,您将需要找到一种方法来解析已存在的行的列(例如,将其设置为NOW()或开始时间)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM