Skip to content

Commit ae05ec8

Browse files
committed
add docs to explain the usage of m2m tracking
1 parent 9d64729 commit ae05ec8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

docs/historical_model.rst

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,3 +419,42 @@ compatibility; it is more correct for a ``FileField`` to be converted to a
419419
420420
SIMPLE_HISTORY_FILEFIELD_TO_CHARFIELD = True
421421
422+
423+
Tracking many to many relationships
424+
-----------------------------------
425+
By default, many to many fields are ignored when tracking changes.
426+
If you want to track many to many relationships, you need to define them explicitly:
427+
428+
.. code-block:: python
429+
430+
class Category(models.Model):
431+
pass
432+
433+
class Poll(models.Model):
434+
question = models.CharField(max_length=200)
435+
categories = models.ManyToManyField(Category)
436+
history = HistoricalRecords(many_to_many=[categories])
437+
438+
This will create a historical intermediate model that tracks each relational change
439+
between `Poll` and `Category`.
440+
441+
You will see the many to many changes when diffing between two historical records:
442+
443+
.. code-block:: python
444+
445+
informal = Category(name="informal questions")
446+
official = Category(name="official questions")
447+
p = Poll.objects.create(question="what's up?")
448+
p.save()
449+
p.categories.add(informal, official)
450+
p.categories.remove(informal)
451+
452+
last_record = p.history.latest()
453+
previous_record = last_record.prev_record()
454+
delta = last_record.diff_against(previous_record)
455+
456+
for change in delta.changes:
457+
print("{} changed from {} to {}")
458+
459+
# Output:
460+
# categories changed from [{'poll': 1, 'category': 1}, { 'poll': 1, 'category': 2}] to [{'poll': 1, 'category': 2}]

0 commit comments

Comments
 (0)