[英]how to automatically add default columns to all django model tables
I have the following 4 columns which I would like to add to all tables: 我有以下4列,我想添加到所有表:
currently I do it the following way: 目前我通过以下方式实现:
from django.db import models
class Table_1(models.Model):
column1 = models.CharField(max_length=64)
column2 = models.CharField(max_length=64)
creationname = models.CharField(max_length=64)
creationdate = models.DateTimeField('creation date', auto_now_add=False)
revisionname = models.CharField(max_length=64)
revisiondate = models.DateTimeField('revision date', auto_now=False)
class Table_2(models.Model):
column1 = models.CharField(max_length=64)
column2 = models.CharField(max_length=64)
creationname = models.CharField(max_length=64)
creationdate = models.DateTimeField('creation date', auto_now_add=False)
revisionname = models.CharField(max_length=64)
revisiondate = models.DateTimeField('revision date', auto_now=False)
...
class Table_n(models.Model):
column1 = models.CharField(max_length=64)
column2 = models.CharField(max_length=64)
creationname = models.CharField(max_length=64)
creationdate = models.DateTimeField('creation date', auto_now_add=False)
revisionname = models.CharField(max_length=64)
revisiondate = models.DateTimeField('revision date', auto_now=False)
can this be acchieved in an automated way, so the 4 columns are automatically appended to each table? 这可以通过自动方式实现,因此4列会自动附加到每个表中吗?
note: is this also achievable for all tables of a django project not just the tables of a single django app? 注意:对于django项目的所有表格而言,这是否也可以实现,而不仅仅是单个django应用程序的表格?
in case this is against django design philosophy please let me know as well 如果这是针对django设计理念,请告诉我
You could use an abstract base model and inheritance to do so: 您可以使用抽象基础模型和继承来执行此操作:
class ModelWithRevisions(models.Model):
creationname = models.CharField(max_length=64)
creationdate = models.DateTimeField('creation date', auto_now_add=False)
revisionname = models.CharField(max_length=64)
revisiondate = models.DateTimeField('revision date', auto_now=False)
class Meta:
abstract = True
class OtherModel(ModelWithRevisions):
column1 = models.CharField(max_length=64)
column2 = models.CharField(max_length=64)
Note that if you're trying to track the history of your models, or track who changed them last, you might want to look into an existing model auditing package . 请注意,如果您尝试跟踪模型的历史记录,或者跟踪最后更改模型的人员,则可能需要查看现有的模型审核包 。
Create a base model. 创建基本模型。 Then extend that model.
然后扩展该模型。
class BaseTable(models.Model):
creationname = models.CharField(max_length=64)
creationdate = models.DateTimeField('creation date', auto_now_add=True)
revisionname = models.CharField(max_length=64)
revisiondate = models.DateTimeField('revision date', auto_now=False)
class Meta:
abstract = True
class Table1(BaseTable):
column1 = models.TextField()
column2 = models.TextField()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.