0Pricing
Django Academy · Aula

prefetch_related para M2M

Carregue dados muitos-para-muitos em lote com eficiência

prefetch_related para M2M é uma aula grátis de Django Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Django Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Django Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Meet prefetch_related

prefetch_related handles the relationships a join cannot, like many-to-many and reverse links, with smart batching. 📦

Two Queries, Not Many

Instead of one giant join, it runs a second query for the related rows, then matches them up in Python.

The Basic Call

Pass the relation name to prefetch_related, just like before, and Django batches the lookups for you automatically.

authors = Author.objects.prefetch_related('books')

Why Two Beats N+1

One query for authors and one for all their books is two trips total, no matter how many authors you loop over.

for author in authors:
    print(author.books.count())

Best for Many

Reach for it whenever each object links to multiple rows: many-to-many fields and reverse foreign keys are perfect fits.

Reverse Relations Work

It shines on reverse accessors, like an author reaching all their books, where select_related simply cannot help.

Mixing Both Tools

You can chain both optimizers on one queryset, using each for the relationship type it handles best.

Book.objects.select_related('author').prefetch_related('tags')

Control with Prefetch

The Prefetch object lets you filter or order the related rows that get fetched, giving you fine control.

from django.db.models import Prefetch
Author.objects.prefetch_related(
  Prefetch('books', queryset=Book.objects.filter(year=2024)))

Done in Python

The matching happens in Python, not SQL. That is why it sidesteps the row explosion a big many-to-many join would cause.

Filter Inside the Loop Carefully

Calling filter on a prefetched set inside a loop fires fresh queries again. Use Prefetch to keep the batching benefit.

Two Tools, One Goal

select_related for single links, prefetch_related for many. Together they crush N+1 in almost any view. 🚀

Quick Check

Choose the right optimizer for this case.

Recap

prefetch_related batches many-to-many and reverse links into a second query, matched in Python. Pair it with select_related for full coverage. ✅

Perguntas Frequentes

A aula “prefetch_related para M2M” é grátis?

Sim — o texto completo de “prefetch_related para M2M” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Django Academy, atualize para CoddyKit PRO. O curso de Django Academy inclui 4 aulas no total.

O que vou aprender em “prefetch_related para M2M”?

Carregue dados muitos-para-muitos em lote com eficiência Você pratica Django Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Django Academy?

Nenhuma experiência prévia é necessária. Django Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “prefetch_related para M2M”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Django Academy?

Sim. Cada aula de Django Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Identificando o problema N+1
  2. select_related para chaves estrangeiras
  3. prefetch_related para M2M
  4. Criação de perfil com a Debug Toolbar
← Voltar para Django Academy