Home > Enterprise >  prefetch by related_name in children foreign key django
prefetch by related_name in children foreign key django

Time:02-12

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')

CodePudding user response:

.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.

  • Related