1
votes

i'm trying to prefetch related from parent model to chidren throught the related name, However the queryset in the template still hits the DB in PostgreSQL, my modelB modelC and ModelD all point towards modelA and when I overwrite the generic class based view queryset function it still doesnt affect the size of the query?? any clues ?

*MODEL
class ModelA(models.Model):
    title = models.Charfield(max_lenght=200, null=True, Blank=True)

class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE, related_name="model_a_related")

*VIEW
class ModelAView(DetailView):
    model = ModelA

    def get_queryset(self):
        return super().get_queryset().prefetch_related('model_a_related')
1
.prefetch_related does not fetches the ModelBs in the same query, but in a second query. For a DetailView, it will not make an improvement: .prefetch_related is useful if you render a set of ModelAs, since then you prevent making a query per ModelA object to fetch the related ModelBs.Willem Van Onsem

1 Answers

1
votes

.prefetch_related(…) [Django-doc] does not fetches the ModelBs in the same query, but in a second query where it fetches all the related ModelBs for the selected (filtered) ModelAs in bulk, this in contract to fetching it per ModelA object which would be the usual behavior.

For a DetailView [Django-doc], it will thus not make any improvement. In a DetailView you render a single item, and fetching the related ModelBs will, regardless whether it is done through .prefetch_related(…) or by accessing object.model_a_related.all() make one extra query.