Skip to content

Commit e2d7670

Browse files
authored
feat: m2m_fields accepts field names (#1243)
1 parent 63bea3b commit e2d7670

File tree

4 files changed

+12
-5
lines changed

4 files changed

+12
-5
lines changed

CHANGES.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Changes
44
Unreleased
55
----------
66

7+
- Allow ``HistoricalRecords.m2m_fields`` as str
78

89
3.4.0 (2023-08-18)
910
------------------

docs/historical_model.rst

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -469,9 +469,12 @@ If you want to track many to many relationships, you need to define them explici
469469
This will create a historical intermediate model that tracks each relational change
470470
between `Poll` and `Category`.
471471

472-
You may also define these fields in a model attribute (by default on `_history_m2m_fields`).
473-
This is mainly used for inherited models. You can override the attribute name by setting
474-
your own `m2m_fields_model_field_name` argument on the `HistoricalRecord` instance.
472+
You may use either the name of the field or the field instance itself.
473+
474+
You may also define these fields in a class attribute (by default on `_history_m2m_fields`).
475+
This is mainly used by inherited models not declaring their own `HistoricalRecord`.
476+
You can override the attribute name by setting your own `m2m_fields_model_field_name`
477+
argument on the `HistoricalRecord` instance.
475478

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

simple_history/models.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -768,7 +768,10 @@ def get_m2m_fields_from_model(self, model):
768768
m2m_fields.update(getattr(model, self.m2m_fields_model_field_name))
769769
except AttributeError:
770770
pass
771-
return [getattr(model, field.name).field for field in m2m_fields]
771+
field_names = [
772+
field if isinstance(field, str) else field.name for field in m2m_fields
773+
]
774+
return [getattr(model, field_name).field for field_name in field_names]
772775

773776

774777
def transform_field(field):

simple_history/tests/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ class Meta:
190190

191191
class PollChildBookWithManyToMany(PollParentWithManyToMany):
192192
books = models.ManyToManyField("Book", related_name="books_poll_child")
193-
_history_m2m_fields = [books]
193+
_history_m2m_fields = ["books"]
194194

195195

196196
class PollChildRestaurantWithManyToMany(PollParentWithManyToMany):

0 commit comments

Comments
 (0)