I'm trying to figure out how to optimize a Django query. I have an queryset that contains a foreign key to exercises. That table makes ManyToMany references to a number of other tables. If selecting exercises, I'd use prefetch_related to include them in the query, but I can't figure out how to do that in this case, since I'm doing it from a different table. Currently, it's being selected as
super().get_queryset(request).select_related('exercise').prefetch_related('exercise__equipments', 'exercise__injuries')
But I can't figure out how to attach prefetch_related to that. Looking at SO, I found a solution that led me to this:
return super().get_queryset(request).select_related(
Prefetch(
'exercise',
queryset=Exercise.objects.prefetch_related('equipments', 'inuries')
)
)
But it fails with 'Prefetch' object has no attribute 'split', which I traced through the source, and it looks like select_related can't work with Prefetch.
EDIT: More info:
- I'm trying to optimize an admin page with a
SortableStackedInline - The starting model is Template
class Template(SortableMixin):
exercise = models.ForeignKey('Exercise', models.CASCADE)
class Exercise(models.Model):
equipments = models.ManyToManyField('Equipment', blank=True, through='ExerciseEquipment')
injuries = models.ManyToManyField('Injury', blank=True, through='ExerciseInjury')
The ultimate goal is to optimize the query from Template through Equipment/Injury