Skip to content

Commit 55decce

Browse files
committed
Make historical records' m2m fields type-compatible with non-historical
Fixes #1186
1 parent b5eadd5 commit 55decce

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

simple_history/manager.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,35 @@ def __get__(self, instance, owner):
127127
return HistoryManager.from_queryset(HistoricalQuerySet)(self.model, instance)
128128

129129

130+
class HistoryManyToManyDescriptor:
131+
def __init__(self, model, rel):
132+
self.rel = rel
133+
self.model = model
134+
135+
def __get__(self, instance, owner):
136+
return HistoryManyRelatedManager.from_queryset(QuerySet)(
137+
self.model, self.rel, instance
138+
)
139+
140+
141+
class HistoryManyRelatedManager(models.Manager):
142+
def __init__(self, through, rel, instance=None):
143+
super().__init__()
144+
self.model = rel.model
145+
self.through = through
146+
self.instance = instance
147+
self._m2m_through_field_name = rel.field.m2m_reverse_field_name()
148+
149+
def get_queryset(self):
150+
qs = super().get_queryset()
151+
through_qs = HistoryManager.from_queryset(HistoricalQuerySet)(
152+
self.through, self.instance
153+
)
154+
return qs.filter(
155+
pk__in=through_qs.all().values_list(self._m2m_through_field_name, flat=True)
156+
)
157+
158+
130159
class HistoryManager(models.Manager):
131160
def __init__(self, model, instance=None):
132161
super().__init__()

simple_history/models.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@
3131
from simple_history import utils
3232

3333
from . import exceptions
34-
from .manager import SIMPLE_HISTORY_REVERSE_ATTR_NAME, HistoryDescriptor
34+
from .manager import (
35+
SIMPLE_HISTORY_REVERSE_ATTR_NAME,
36+
HistoryDescriptor,
37+
HistoryManyToManyDescriptor,
38+
)
3539
from .signals import (
3640
post_create_historical_m2m_records,
3741
post_create_historical_record,
@@ -227,7 +231,7 @@ def finalize(self, sender, **kwargs):
227231

228232
setattr(module, m2m_model.__name__, m2m_model)
229233

230-
m2m_descriptor = HistoryDescriptor(m2m_model)
234+
m2m_descriptor = HistoryManyToManyDescriptor(m2m_model, field.remote_field)
231235
setattr(history_model, field.name, m2m_descriptor)
232236

233237
def get_history_model_name(self, model):

0 commit comments

Comments
 (0)