Search code examples
djangodjango-migrationsdjango-simple-history

Write migration changes to django simple history


django-simple-history writing history changes on instance.save() method. But when I wrote migration which change instance data, the changes did not appear.

Is the save() method of

Model = apps.get_model('myapp', 'MyModel') 

and

MyModel 

are same? Is there a way to write this changes to history?


Solution

  • django-simple-history uses a post_save signal on MyModel in order to save to the historical table. That signal isn't sent in your migrations, so you want to write directly to the historical table. You'll have to include a history_date field for the historical table. The below should work:

    from datetime import datetime
    Model = apps.get_model('myapp', 'MyModel')
    HistoricalModel = apps.get_model('myapp', 'HistoricalMyModel')
    
    instance = Model.objects.create(name='Test')
    HistoricalModel.objects.create(name=instance.name, id=instance.id, history_date=datetime.now())