Skip to content Skip to sidebar Skip to footer

History Of A Manytomanyfield In Django-simple-history

Story short, I need to save in the history the changes made on a Many-To-Many fields of one of my models. I can see from: https://github.com/Kyruus/django-simple-history/commit/5ba

Solution 1:

This is an old open question, and might be irrelevant by now, but from looking into the code of the project in question, it seems like the last line on the ClassRoom model should be changed to

history = HistoricalRecords(m2m_fields=['students'])

Solution 2:

Since m2m_fields is actually not available in the standard branch, here's an alternative solution using the django-simple-history package.

You can manually create the many to many table and instead of using djangos add and remove you simply create and delete the relations. If you look at it with an example we would have:

class Student(models.Model):
  studentname = models.CharField(max_length=50, verbose_name='Name')

class ClassRoom(models.Model):
  classname = models.CharField(max_length=50, verbose_name='Name')
  history = HistoricalRecords()

class StudentClassRooms(models.Model):
    student = models.ForeignKey(Student)
    classroom = models.ForeignKey(ClassRoom)
    history = HistoricalRecords()

if you now use:

StudentClassRooms.objects.create(student=student, classroom=classroom) instead of classroom.students.add(student) and delete() instead of classroom.student.remove(student) you will have everything tracked in a history table and the same many to many table.

Post a Comment for "History Of A Manytomanyfield In Django-simple-history"