I have the following models:
class Block(MPTTModel):
# some fields
links = models.ManyToManyField('self', through='BlockLink', symmetrical=False)
class BlockLink(models.Model):
source = models.ForeignKey(
'Block', on_delete=models.CASCADE, related_name='source_block'
)
destination = models.ForeignKey(
'Block', on_delete=models.PROTECT, related_name='destination_block', null=True
)
is_valid = models.BooleanField(default=False)
With that, I can access the through model using:
my_block.links.through.objects.filter(source=my_block.id)
My problem is, that I access the blocks in a loop, and each of the blocks creates an own query to select the through model. So for 5000 blocks, we have 5000 additional queries.
How can prevent this. Is there any way of annotating or prefetching the through model?
What I tried?
I tried the solution from Django prefetch through table using .prefetch_related('blocklink_set')
but that ends up in the following error:
Cannot find 'blocklink_set' on Block object, 'blocklink_set' is an invalid parameter to prefetch_related()
Second try was
.prefetch_related(
Prefetch('blocklink', queryset=BlockLink.objects.all()),
)
but that also ends in an error.