@@ -447,3 +447,42 @@ And you don't want to create database index for ``question``, it is necessary to
447
447
448
448
By default, django-simple-history keeps all indices. and even forces them on unique fields and relations.
449
449
WARNING: This will drop performance on historical lookups
450
+
451
+ Tracking many to many relationships
452
+ -----------------------------------
453
+ By default, many to many fields are ignored when tracking changes.
454
+ If you want to track many to many relationships, you need to define them explicitly:
455
+
456
+ .. code-block :: python
457
+
458
+ class Category (models .Model ):
459
+ pass
460
+
461
+ class Poll (models .Model ):
462
+ question = models.CharField(max_length = 200 )
463
+ categories = models.ManyToManyField(Category)
464
+ history = HistoricalRecords(many_to_many = [categories])
465
+
466
+ This will create a historical intermediate model that tracks each relational change
467
+ between `Poll ` and `Category `.
468
+
469
+ You will see the many to many changes when diffing between two historical records:
470
+
471
+ .. code-block :: python
472
+
473
+ informal = Category(name = " informal questions" )
474
+ official = Category(name = " official questions" )
475
+ p = Poll.objects.create(question = " what's up?" )
476
+ p.save()
477
+ p.categories.add(informal, official)
478
+ p.categories.remove(informal)
479
+
480
+ last_record = p.history.latest()
481
+ previous_record = last_record.prev_record()
482
+ delta = last_record.diff_against(previous_record)
483
+
484
+ for change in delta.changes:
485
+ print (" {} changed from {} to {} " )
486
+
487
+ # Output:
488
+ # categories changed from [{'poll': 1, 'category': 1}, { 'poll': 1, 'category': 2}] to [{'poll': 1, 'category': 2}]
0 commit comments