NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior79 views

Вы хорошо объяснили выбор между select_related и prefetch_related. А можете привести пример, когда использование prefetch_related может привести к ухудшению производительности?

Practice

Asked at

AI answer

prefetch_related can hurt performance if the relationship returns a very large number of records. For example, when loading thousands of orders with their items, Django will execute an additional query for all the items and store them in memory. If you need only the orders themselves or a small subset of items, the costs of querying, transferring data, and memory may outweigh the benefit of reducing the number of queries.

Another common case is prefetching the entire relationship and then accessing a filtered version of it: order.items.filter(active=True) will execute a new query, and the prefetched items will not be used. Consider limiting the set with Prefetch and an appropriate queryset, loading only the fields you need, or choosing another way to retrieve the data.