Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefetc_related on a field with tracker fails #433

Closed
mahsa-lotfi92 opened this issue Jun 24, 2020 · 1 comment
Closed

Prefetc_related on a field with tracker fails #433

mahsa-lotfi92 opened this issue Jun 24, 2020 · 1 comment

Comments

@mahsa-lotfi92
Copy link

Problem

Running prefetch_related on a column which has a tracker will be failed with this error:

ValueError: "prefetch_related_field_name" does not resolve to an item that supports prefetching - this is an invalid parameter to prefetch_related().

Environment

  • Django Model Utils version: 4.0.0
  • Django version: 2.2
  • Python version: 3.8
  • Other libraries used, if any: nothing.

Code examples

Given this code in models.py

from django.db import models
from model_utils import FieldTracker
class A(models.Model):
    name = models.CharField(max_length=10)


class B(models.Model):
    name = models.CharField(max_length=10)


class C(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    b = models.ForeignKey(B, on_delete=models.CASCADE)
    tracker = FieldTracker(fields=('b',))

This is the test case to reproduce the error:

from django.test import TestCase
from models import *


class TestTracker(TestCase):
    def test_tracker(self):
        a = A.objects.create(name='something')
        b = B.objects.create(name='something')
        C.objects.create(a=a, b=b)
        print(A.objects.prefetch_related('c_set__b').all())

and this is the error:

ValueError: 'c_set__b' does not resolve to an item that supports prefetching - this is an invalid parameter to prefetch_related().

I debugged and found that when running the executing prefetch in Django, rel_obj_descriptor is tracker.DescriptorWrapper instead of ForwardManyToOneDescriptor which does not have the mehtod get_prefetch_queryset

@IBestuzhev
Copy link

As a workaround, I managed to have Tracker + Prefetch working together by adding this lines:

C.b.get_prefetch_queryset = C.b.descriptor.get_prefetch_queryset
C.b.is_cached = C.b.descriptor.is_cached

But I guess the correct fix is to alter DescriptorWrapper. It should include something like

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

marcari added a commit to marcari/django-model-utils that referenced this issue Sep 29, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants