0Pricing
Django Academy · Aula

ModelViewSet e roteadores

Gere rotas CRUD automaticamente

ModelViewSet e roteadores é uma aula grátis de Django Academy no CoddyKit. Esta é a aula 1 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.

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 = BookSerializer

Two 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! 🎉

Perguntas Frequentes

A aula “ModelViewSet e roteadores” é grátis?

Sim — o texto completo de “ModelViewSet e roteadores” é 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 “ModelViewSet e roteadores”?

Gere rotas CRUD automaticamente 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 1 de 4.

Quanto tempo leva a aula “ModelViewSet e roteadores”?

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. ModelViewSet e roteadores
  2. Permissões e limitação de requisições
  3. Autenticação por token e JWT
  4. Filtragem, pesquisa e paginação
← Voltar para Django Academy