Skip to content

Commit

Permalink
Make historical records' m2m fields type-compatible with non-historical
Browse files Browse the repository at this point in the history
Fixes #1186
  • Loading branch information
mjsir911 committed Aug 18, 2023
1 parent b5eadd5 commit 55decce
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
29 changes: 29 additions & 0 deletions simple_history/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,35 @@ def __get__(self, instance, owner):
return HistoryManager.from_queryset(HistoricalQuerySet)(self.model, instance)


class HistoryManyToManyDescriptor:
def __init__(self, model, rel):
self.rel = rel
self.model = model

def __get__(self, instance, owner):
return HistoryManyRelatedManager.from_queryset(QuerySet)(
self.model, self.rel, instance
)


class HistoryManyRelatedManager(models.Manager):
def __init__(self, through, rel, instance=None):
super().__init__()
self.model = rel.model
self.through = through
self.instance = instance
self._m2m_through_field_name = rel.field.m2m_reverse_field_name()

def get_queryset(self):
qs = super().get_queryset()
through_qs = HistoryManager.from_queryset(HistoricalQuerySet)(
self.through, self.instance
)
return qs.filter(
pk__in=through_qs.all().values_list(self._m2m_through_field_name, flat=True)
)


class HistoryManager(models.Manager):
def __init__(self, model, instance=None):
super().__init__()
Expand Down
8 changes: 6 additions & 2 deletions simple_history/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@
from simple_history import utils

from . import exceptions
from .manager import SIMPLE_HISTORY_REVERSE_ATTR_NAME, HistoryDescriptor
from .manager import (
SIMPLE_HISTORY_REVERSE_ATTR_NAME,
HistoryDescriptor,
HistoryManyToManyDescriptor,
)
from .signals import (
post_create_historical_m2m_records,
post_create_historical_record,
Expand Down Expand Up @@ -227,7 +231,7 @@ def finalize(self, sender, **kwargs):

setattr(module, m2m_model.__name__, m2m_model)

m2m_descriptor = HistoryDescriptor(m2m_model)
m2m_descriptor = HistoryManyToManyDescriptor(m2m_model, field.remote_field)
setattr(history_model, field.name, m2m_descriptor)

def get_history_model_name(self, model):
Expand Down

0 comments on commit 55decce

Please sign in to comment.