5

How to make history for a model that show me the old value and the new changed value in a field?

In my mind i think to make history model to each model which have the same fields and when the user create new or update the data from the first model go to the second model too.

I searched alot for this problem and i found a packet called django-reversion but i didn't understand it how to make it store the old value and new value if any one can help me for this problem please tell me.

Ralf
  • 16,086
  • 4
  • 44
  • 68

3 Answers3

3

For this purpose you can use simple-history app

Every changes of your instance will be reflected in historical table. There would be new row with new values for each changes. so you can reproduce all old values for each field.

Danil
  • 4,781
  • 1
  • 35
  • 50
2

In this link there is a comparisson of different packages that can be used for audit/history of models.

I use django-simple-history which comes with a nice integration to view the list of changes of every model instance in the admin.

For my use case at least, django-simple-history provided me with what I needed, and so far I did not face any issues with it.


EDIT: just an additional note

This package does NOT track history of ManyToManyField.

See also these related questions:

  1. How can I store history of ManyToManyField using django-simple-history.
  2. History of a ManyToManyField in django-simple-history

And the Github issue:

  1. https://github.com/treyhunner/django-simple-history/issues/16
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • but i think django simple history just notification you which field changed but not store the old value changed in this field .. – Ahmed Othman Mohamed Nazim Apr 26 '18 at 19:15
  • @AhmedOthmanMohamedNazim Incorrect: this extension creates a copy of your model (makes a new migration which creates a new table) and stores all the old values. Additionally it stores user and datetime of the changes to each instance of the model. – Ralf Apr 26 '18 at 19:19
  • Also: If you add fields to your model, the History table will get changed as well to add that new field. – Ralf Apr 26 '18 at 19:20
  • cool okay i will try it .. if this extension really do that .. this will be what i search about .. i will try it and answer you .. thank you – Ahmed Othman Mohamed Nazim Apr 29 '18 at 09:11
  • @AhmedOthmanMohamedNazim I edited my answer to include info about `ManyToManyField` – Ralf Apr 29 '18 at 15:46
1

There may be a clean library that does everything you need, I just don't know.

How I'd approach this problem is overriding the model save function. You can refer to this prior stackoverflow post to get the gist of what is going on. In this way you could specify which model class/ sql table you'd like to apply memory for. And then add to the custom save method to create a new row in the new change log model class.

sahutchi
  • 2,223
  • 2
  • 19
  • 20