Skip to content

Commit b6859db

Browse files
committed
Replace id by pk to properly handle models with custom primary keys
1 parent 2521e54 commit b6859db

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

src/dirtyfields/dirtyfields.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def _as_dict_m2m(self):
6969
if self.pk:
7070
m2m_fields = dict([
7171
(f.attname, set([
72-
obj.id for obj in getattr(self, f.attname).all()
72+
obj.pk for obj in getattr(self, f.attname).all()
7373
]))
7474
for f, model in get_m2m_with_model(self.__class__)
7575
])

tests/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,14 @@ class TestM2MModel(DirtyFieldsMixin, models.Model):
7070
m2m_field = models.ManyToManyField(TestModel)
7171

7272

73+
class TestModelWithCustomPK(DirtyFieldsMixin, models.Model):
74+
custom_primary_key = models.CharField(max_length=80, primary_key=True)
75+
76+
77+
class TestM2MModelWithCustomPKOnM2M(DirtyFieldsMixin, models.Model):
78+
m2m_field = models.ManyToManyField(TestModelWithCustomPK)
79+
80+
7381
class TestModelWithPreSaveSignal(DirtyFieldsMixin, models.Model):
7482
data = models.CharField(max_length=10)
7583
data_updated_on_presave = models.CharField(max_length=10, blank=True, null=True)

tests/test_m2m_fields.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import pytest
22

3-
from .models import TestModel, TestM2MModel
3+
from .models import TestModel, TestM2MModel, TestModelWithCustomPK, TestM2MModelWithCustomPKOnM2M
44

55

66
@pytest.mark.django_db
@@ -21,3 +21,14 @@ def test_dirty_fields_on_m2m():
2121

2222
assert tm.get_dirty_fields(check_m2m={'m2m_field': set([0, tm2.id])}) == {'m2m_field': set([tm2.id])}
2323

24+
25+
@pytest.mark.django_db
26+
def test_m2m_check_with_custom_primary_key():
27+
# test for bug: https://github.com/romgar/django-dirtyfields/issues/74
28+
29+
tm = TestModelWithCustomPK.objects.create(custom_primary_key='pk1')
30+
m2m_model = TestM2MModelWithCustomPKOnM2M.objects.create()
31+
32+
# This line was triggering this error:
33+
# AttributeError: 'TestModelWithCustomPK' object has no attribute 'id'
34+
m2m_model.m2m_field.add(tm)

0 commit comments

Comments
 (0)