I have the following 4 columns which I would like to add to all tables:
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?
note: is this also achievable for all tables of a django project not just the tables of a single django app?
in case this is against django design philosophy please let me know as well
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.