prefetch_related para M2M
Cargue datos de relaciones muchos a muchos por lotes de forma eficiente
prefetch_related para M2M es una lección gratuita de Django Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Django Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Django Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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. ✅
Preguntas frecuentes
¿La lección «prefetch_related para M2M» es gratis?
Sí — el texto completo de «prefetch_related para M2M» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Django Academy, actualiza a CoddyKit PRO. El curso de Django Academy incluye 4 lecciones en total.
¿Qué aprenderé en «prefetch_related para M2M»?
Cargue datos de relaciones muchos a muchos por lotes de forma eficiente Practicas Django Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Django Academy?
No se requiere experiencia previa. Django Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «prefetch_related para M2M»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Django Academy?
Sí. Cada lección de Django Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Detección del problema N+1
- select_related para Foreign Keys
- prefetch_related para M2M
- Perfilado con Debug Toolbar