ModelViewSet y Routers
Genere rutas CRUD automáticamente
ModelViewSet y Routers es una lección gratuita de Django Academy en CoddyKit. Esta es la lección 1 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.
The CRUD Repetition Problem
Writing list, create, retrieve, update, and delete by hand means a lot of near-identical code. A ViewSet bundles all of it into one tidy class.
Meet ModelViewSet
The ModelViewSet gives you full CRUD for a model with almost no code. Point it at a queryset and a serializer, and it handles the rest.
from rest_framework import viewsets
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializerTwo Attributes Do the Work
Those two lines carry the whole class. queryset says which rows are in play, and serializer_class says how to turn them into JSON. 📦
The Actions You Get Free
A ModelViewSet provides five actions: list, create, retrieve, update, partial_update, and destroy. You wrote none of them by hand.
Why Routers Exist
A ViewSet groups actions, but URLs still need wiring. A router reads your ViewSet and generates every URL pattern automatically.
Registering with DefaultRouter
Create a DefaultRouter, register your ViewSet under a prefix, and it builds the full URL set for you.
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'books', BookViewSet)Plugging Router URLs In
The router exposes router.urls, a ready list of patterns. Add it to your urlpatterns and the endpoints go live instantly.
urlpatterns = [
path('api/', include(router.urls)),
]The URLs You Just Created
Registering one ViewSet gives you /books/ for the list and create, plus /books/{id}/ for retrieve, update, and delete. 🚀
HTTP Verbs Map to Actions
The router maps verbs to actions: GET lists, POST creates, GET on an id retrieves, PUT or PATCH updates, and DELETE destroys. One ViewSet, six behaviors.
DefaultRouter vs SimpleRouter
DefaultRouter adds a handy API root view that lists your endpoints. SimpleRouter skips it when you want a leaner URL set.
Adding a Custom Action
Need an extra endpoint? The @action decorator adds a custom route to a ViewSet without leaving the class.
from rest_framework.decorators import action
@action(detail=True, methods=['post'])
def favorite(self, request, pk=None):
...Quick Check
Time to lock in how ViewSets and routers fit together.
Recap: CRUD in a Few Lines
You learned that a ModelViewSet plus a router turns two short classes into a complete CRUD API, with clean URLs generated for you. Nicely done! 🎉
Preguntas frecuentes
¿La lección «ModelViewSet y Routers» es gratis?
Sí — el texto completo de «ModelViewSet y Routers» 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 «ModelViewSet y Routers»?
Genere rutas CRUD automáticamente 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 1 de 4.
¿Cuánto tiempo toma la lección «ModelViewSet y Routers»?
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
- ModelViewSet y Routers
- Permisos y limitación de solicitudes
- Autenticación con tokens y JWT
- Filtrado, búsqueda y paginación