简体   繁体   中英

prefetch by related_name in children foreign key django

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

.prefetch_related(…) [Django-doc] does not fetches the ModelB s in the same query, but in a second query where it fetches all the related ModelB s for the selected (filtered) ModelA s 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 ModelB s will, regardless whether it is done through .prefetch_related(…) or by accessing object.model_a_related.all() make one extra query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM