Skip to content

m2m_fields throws exception when relation is modified using reverse acessor #1048

Open
@amanz360

Description

@amanz360

Describe the bug
I'm attempting to use the new m2m_fields released in version 3.2.0 but it doesn't appear to handle the m2m related manager on both models properly.

To Reproduce
Steps to reproduce the behavior:
Toy example based on my actual issue

class Lot(models.Model):
    pass

class Shipment(models.Model):
    lots = models.ManyToManyField("Lot", related_name="shipments")
    history = HistoricalRecords(m2m_fields=[lots])

With this relationship and having generated the appropriate migration after, I ran into an exception when existing code attempted to insert records into the through table via the shipments accessor on the Lot model that django would provide

Traceback (most recent call last):
  File "/builds/xxx/xxx-server/xxx/tests/test_daily_brand_alert.py", line 383, in test_forecasted_out_of_stock_alerts
    self.lots1.shipments.add(self.shipment1)
  File "/venvs/xxx/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 950, in add
    self._add_items(
  File "/venvs/xxx/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 1159, in _add_items
    signals.m2m_changed.send(
  File "/venvs/xxx/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 180, in send
    return [
  File "/venvs/xxx/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp>
    (receiver, receiver(signal=self, sender=sender, **named))
  File "/venvs/xxx/lib/python3.9/site-packages/simple_history/models.py", line 637, in m2m_changed
    self.create_historical_record(instance, "~")
  File "/venvs/xxx/lib/python3.9/site-packages/simple_history/models.py", line 698, in create_historical_record
    self.create_historical_record_m2ms(history_instance, instance)
  File "/venvs/xxx/lib/python3.9/site-packages/simple_history/models.py", line 643, in create_historical_record_m2ms
    through_model = getattr(original_instance, field.name).through
AttributeError: 'Lot' object has no attribute 'lots'

Expected behavior
I'd expect defining the m2m_fields on one model to record changes made via the corresponding model without exception

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssues related to confirmed bugs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions