Skip to content

Commit

Permalink
Merge pull request #555 from joeriddles/fix-prefetch-related
Browse files Browse the repository at this point in the history
Fix `ValueError` when calling `prefetch_related` for tracked `ForeignKey` fields
  • Loading branch information
joeriddles authored Dec 16, 2023
2 parents 11de64b + 55cd816 commit 74a064d
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
| Jannis Leidel <[email protected]>
| Javier Garcia Sogo <[email protected]>
| Jeff Elmore <[email protected]>
| Joe Riddle <[email protected]>
| John Vandenberg <[email protected]>
| Jonathan Sundqvist <[email protected]>
| João Amaro <[email protected]>
Expand Down
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ To be released
- Drop support for `Python 3.7` (GH-#545)
- Swedish translation (GH-#561)
- Use proper column name instead of attname (GH-#573)
- Fix `ValueError` when calling `prefetch_related` for tracked `ForeignKey` fields (Fixes GH-433)

4.3.1 (2022-11-15)
------------------
Expand Down
3 changes: 3 additions & 0 deletions model_utils/tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ def __set__(self, instance, value):
else:
instance.__dict__[self.field_name] = value

def __getattr__(self, attr):
return getattr(self.descriptor, attr)

@staticmethod
def cls_for_descriptor(descriptor):
if hasattr(descriptor, '__delete__'):
Expand Down
23 changes: 23 additions & 0 deletions tests/test_fields/test_field_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,29 @@ def test_custom_without_id(self):
self.assertCurrent(fk=self.instance.fk_id)


class FieldTrackerForeignKeyPrefetchRelatedTests(FieldTrackerTestCase):
"""Test that using `prefetch_related` on a tracked field does not raise a ValueError."""

fk_class = Tracked
tracked_class = TrackedFK

def setUp(self):
model_tracked = self.fk_class.objects.create(name="", number=0)
self.instance = self.tracked_class.objects.create(fk=model_tracked)

def test_default(self):
self.tracker = self.instance.tracker
self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk")))

def test_custom(self):
self.tracker = self.instance.custom_tracker
self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk")))

def test_custom_without_id(self):
self.tracker = self.instance.custom_tracker_without_id
self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk")))


class FieldTrackerTimeStampedTests(FieldTrackerTestCase):

fk_class = Tracked
Expand Down

0 comments on commit 74a064d

Please sign in to comment.