Sistema de Gestión de Cursos con Django y DRF
1. Configuración del Proyecto
Paso 1: Crear el proyecto y entorno virtual
mkdir course_management
cd course_management
python -m venv env
source venv/bin/activate
pip install django djangorestframework
Paso 2: Crear el proyecto y la aplicación
django-admin startproject config .
python manage.py startapp courses
Paso 3: Configurar INSTALLED_APPS
Editar config/settings.py:
= [
INSTALLED_APPS
...'rest_framework',
'courses',
]
Paso 4: Migrar la base de datos
python manage.py migrate
2. Modelos
Paso 1: Definir los modelos
Editar courses/models.py:
from django.db import models
class Course(models.Model):
= models.CharField(max_length=100)
title = models.TextField()
description
def __str__(self):
return self.title
class Student(models.Model):
= models.CharField(max_length=100)
name = models.EmailField(unique=True)
email = models.ManyToManyField(Course, related_name='students')
courses
def __str__(self):
return self.name
Paso 2: Migrar los modelos
python manage.py makemigrations
python manage.py migrate
3. Serializers
Paso 1: Crear el archivo serializers.py
Crear y editar courses/serializers.py:
from rest_framework import serializers
from .models import Course, Student
class CourseSerializer(serializers.ModelSerializer):
class Meta:
= Course
model = '__all__'
fields
class StudentSerializer(serializers.ModelSerializer):
class Meta:
= Student
model = '__all__' fields
4. Vistas
Paso 1: Crear las vistas
Editar courses/views.py:
from rest_framework.viewsets import ModelViewSet
from .models import Course, Student
from .serializers import CourseSerializer, StudentSerializer
class CourseViewSet(ModelViewSet):
= Course.objects.all()
queryset = CourseSerializer
serializer_class
class StudentViewSet(ModelViewSet):
= Student.objects.all()
queryset = StudentSerializer serializer_class
5. Rutas
Paso 1: Configurar las rutas de la aplicación
Crear y editar courses/urls.py:
from rest_framework.routers import DefaultRouter
from .views import CourseViewSet, StudentViewSet
= DefaultRouter()
router 'courses', CourseViewSet)
router.register('students', StudentViewSet)
router.register(
= router.urls urlpatterns
Paso 2: Incluir las rutas en el proyecto
Editar config/urls.py:
from django.contrib import admin
from django.urls import path, include
= [
urlpatterns 'admin/', admin.site.urls),
path('api/', include('courses.urls')),
path( ]
6. Pruebas de la API
Paso 1: Levantar el servidor
python manage.py runserver
Paso 2: Endpoints disponibles
Listar Cursos: GET http://127.0.0.1:8000/api/courses/
Crear Curso: POST http://127.0.0.1:8000/api/courses/
{
"title": "Curso Django",
"description": "Aprende Django desde cero."
}
Listar Estudiantes: GET http://127.0.0.1:8000/api/students/
Crear Estudiante: POST http://127.0.0.1:8000/api/students/