Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 809
Arpit Avatar asked Dec 06 '25 04:12

Arpit


1 Answers

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".

like image 96
Willem Van Onsem Avatar answered Dec 08 '25 19:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!