Django's prefetch_related can add queries instead of saving them, benchmarks show
A Django developer discovered that using prefetch_related with certain queryset methods like filter(), order_by(), and first() generates one extra database query per parent object rather than using the prefetched cache. Benchmarks across Django 4.2 and 6.1 confirmed that operations which modify the underlying queryset bypass the cache entirely, while count() and exists() correctly use it. For ten orders, a loop using order.lines.filter() produced twelve queries instead of the expected two, making the prefetch a net loss. The recommended fix is to move filtering conditions into a Prefetch object with a to_attr argument, reducing total queries to two regardless of dataset size. When the cache cannot satisfy the access pattern, removing prefetch_related entirely is advised over paying its cost and re-querying anyway.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in