Search code examples
djangopython-3.6django-simple-history

Problem in Creating history record using Django Simple History


Why Django-Simple history records get created on calling save method if I call update then it doesn't create history record ?

Django : 1.11.15 Django-simple-history : 1.9.0 Python : 3.6


Solution

  • As is written in the documentation this is a known issue:

    Django Simple History functions by saving history using a post_save signal every time that an object with history is saved. However, for certain bulk operations, such as bulk_create and queryset updates, signals are not sent, and the history is not saved automatically. However, Django Simple History provides utility functions to work around this.

    So basically the app makes use of the fact that you .save() the model, and this is circumvented by some ORM calls (because then you can not perform the actions in "bulk" at the database level anymore).

    Instead of using

    Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
    

    you thus need to perform:

    for e in Entry.objects.filter(pub_date__year=2010):
        e.comments_on = False
        e.save()

    For a bulk_create there is a variant: bulk_create_with_history, since then it simply makes two bulk creates: one for the objects, and one for the "histories".