python_beg2
python_beg2

Reputation: 309

Auto save into database django

I have a simple DB schema:

class testModel(models.Model):
    modified_by = models.CharField(max_length=50, verbose_name="Modified by")
    modify_date = models.DateTimeField(auto_now_add=True, auto_now=False)
    week = models.DateField( verbose_name="Week date" )
    type = models.CharField(max_length=10, verbose_name="Type")
    value = models.CharField(max_length=4, verbose_name="value")

    def __unicode__(self):
        return str(self.type)

what i want to do is save each action into second table , e.g. testModel_history.

I know I can create such table and import record during each change in first table, but I would like to ask you whether is there the better way to do this ?

Thanks in advance,

Upvotes: 0

Views: 1026

Answers (2)

naren
naren

Reputation: 15253

If you really are trying to save only history of actions use Django simple history. https://django-simple-history.readthedocs.io/en/latest/usage.html

Allyou need to do is add history = HistoricalRecords() to all the models you need to track

Eg:

class testModel(models.Model):
    modified_by = models.CharField(max_length=50, verbose_name="Modified by")
    modify_date = models.DateTimeField(auto_now_add=True, auto_now=False)
    week = models.DateField( verbose_name="Week date" )
    type = models.CharField(max_length=10, verbose_name="Type")
    value = models.CharField(max_length=4, verbose_name="value")

    history = HistoricalRecords()

    def __unicode__(self):
        return str(self.type)

Upvotes: 0

Max M
Max M

Reputation: 581

Try with an inherited model:

class testModel2(testModel):
    def __init__(testModelObj, self):
        #for every field: self.field_name = testModelObj.field_name

    class Meta:
        db_table = 'your_db_table' #if you want a specific one

Additionally rewrite the save method in testModel:

#in class testModel
def save(self):
    testModel2(self).save()
    super().save()

Upvotes: 1

Related Questions