Prefetch 'to_attr' attribute results in an Attribute not found error

Hey folks,

I have a model setup like this

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

class A(models.Model):
    b = models.ForeignKey(B, on_delete=models.CASCADE)

class C(models.Model):
    b = models.ForeignKey(B, related_name='c', on_delete=models.CASCADE)

and I am trying to run a query

qs = A.objects.filter().prefetch_related(Prefetch('b__c', queryset=C.objects.all(), to_attr='test'))

but when I try to access qs[0].test I get an Attribute error saying model has no attribute test

I’m not sure what I am doing wrong here and I’m on 4.2

I believe you need to access qs[0].b.test because the prefetched relation is related to instances of B.

1 Like

hey, thanks, this was it, I assumed it would be accessible from the parent queryset since that’s where we are calling the Prefetch from from.