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

Вы хорошо описали последовательность действий и диагностику. Расскажите, как именно вы используете select_related и prefetch_related для оптимизации запросов в Django ORM?

Practice

Asked at

AI answer

select_related() and prefetch_related() reduce the number of queries, but they are suited to different relationships.

  • Use select_related() for ForeignKey and OneToOneField. Django performs an SQL JOIN and fetches the related objects in a single query:
    orders = Order.objects.select_related("customer")
    for order in orders:
        print(order.customer.name)
    
  • prefetch_related() is suited to ManyToManyField and reverse one-to-many relationships. Django runs a separate query for the related objects and then joins the results in Python:
    authors = Author.objects.prefetch_related("books")
    for author in authors:
        print([book.title for book in author.books.all()])
    

Without these methods, accessing relationships in a loop often leads to the N+1 problem. You can combine both methods; for complex cases, Prefetch lets you customize the separate query, for example, by filtering related objects.