Skip to content

Commit

Permalink
feat: m2m_fields accepts field names
Browse files Browse the repository at this point in the history
  • Loading branch information
legau committed Sep 4, 2023
1 parent 4c66351 commit 35737fb
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Changes
Unreleased
----------

- Allow ``HistoricalRecords.m2m_fields`` as str

3.4.0 (2023-08-18)
------------------
Expand Down
9 changes: 6 additions & 3 deletions docs/historical_model.rst
Original file line number Diff line number Diff line change
Expand Up @@ -469,9 +469,12 @@ If you want to track many to many relationships, you need to define them explici
This will create a historical intermediate model that tracks each relational change
between `Poll` and `Category`.

You may also define these fields in a model attribute (by default on `_history_m2m_fields`).
This is mainly used for inherited models. You can override the attribute name by setting
your own `m2m_fields_model_field_name` argument on the `HistoricalRecord` instance.
You may use either the name of the field or the field instance itself.

You may also define these fields in a class attribute (by default on `_history_m2m_fields`).
This is mainly used by inherited models not declaring their own `HistoricalRecord`.
You can override the attribute name by setting your own `m2m_fields_model_field_name`
argument on the `HistoricalRecord` instance.

You will see the many to many changes when diffing between two historical records:

Expand Down
5 changes: 4 additions & 1 deletion simple_history/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -768,7 +768,10 @@ def get_m2m_fields_from_model(self, model):
m2m_fields.update(getattr(model, self.m2m_fields_model_field_name))
except AttributeError:
pass
return [getattr(model, field.name).field for field in m2m_fields]
field_names = [
field if isinstance(field, str) else field.name for field in m2m_fields
]
return [getattr(model, field_name).field for field_name in field_names]


def transform_field(field):
Expand Down
2 changes: 1 addition & 1 deletion simple_history/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ class Meta:

class PollChildBookWithManyToMany(PollParentWithManyToMany):
books = models.ManyToManyField("Book", related_name="books_poll_child")
_history_m2m_fields = [books]
_history_m2m_fields = ["books"]


class PollChildRestaurantWithManyToMany(PollParentWithManyToMany):
Expand Down

0 comments on commit 35737fb

Please sign in to comment.