Saltar al contenido

# creacion-de-aplicaciones-web-en-django-y-python

Creación de Aplicaciones Web en Django y Python

Volver a la portada del curso
Video instructor

Migraciones de Base de Datos

Sección 3 · Modelos y Bases de Datos

En este video

  • Entiendes el camino de una migración: del modelo a makemigrations, que escribe el archivo, y a migrate, que crea las tablas
  • Corres makemigrations y lees 0001_initial.py, con sus dependencies y sus tres operaciones CreateModel
  • Revisas con sqlmigrate el CREATE TABLE de catalogo_producto, y con migrate aplicas 19 migraciones
  • Consultas el estado con showmigrations y agregas el campo destacado, que genera una segunda migración con AddField
  • Aprendes dos reglas: no modificar las tablas a mano y guardar las migraciones en git
catalogo/models.py
# Continúa el proyecto del video anterior. Modelos de la lección «Definición de Modelos».
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse


class Categoria(models.Model):
    nombre = models.CharField(max_length=60, unique=True)
    slug = models.SlugField(unique=True)

    class Meta:
        ordering = ["nombre"]

    def __str__(self):
        return self.nombre


class Producto(models.Model):
    categoria = models.ForeignKey(
        Categoria, on_delete=models.PROTECT, related_name="productos"
    )
    nombre = models.CharField(max_length=120)
    slug = models.SlugField(unique=True)
    precio = models.DecimalField(max_digits=8, decimal_places=2)
    stock = models.PositiveIntegerField(default=0)
    disponible = models.BooleanField(default=True)
    creado = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["nombre"]

    def __str__(self):
        return self.nombre

    def get_absolute_url(self):
        return reverse("catalogo:detalle", args=[self.slug])


class Resena(models.Model):
    producto = models.ForeignKey(
        Producto, on_delete=models.CASCADE, related_name="resenas"
    )
    autor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    calificacion = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)]
    )
    comentario = models.TextField(max_length=500)
    creada = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-creada"]

    def __str__(self):
        return f"{self.producto} ({self.calificacion})"
terminal
python manage.py makemigrations catalogo
# Salida:
# Migrations for 'catalogo':
# catalogo\migrations\0001_initial.py
# + Create model Categoria
# + Create model Producto
# + Create model Resena
# El archivo 0001_initial.py lo genera Django: no se escribe a mano.

python manage.py sqlmigrate catalogo 0001
# Salida:
# BEGIN;
# -- Create model Producto
# CREATE TABLE "catalogo_producto" (
# "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
# "nombre" varchar(120) NOT NULL,
# "precio" decimal NOT NULL,
# "disponible" bool NOT NULL, (...));
# COMMIT;

python manage.py migrate
# Salida:
# Operations to perform:
# Apply all migrations: admin, auth, catalogo,
# contenttypes, sessions
# Running migrations:
# Applying contenttypes.0001_initial... OK
# Applying auth.0001_initial... OK
# (...)
# Applying catalogo.0001_initial... OK
# Applying sessions.0001_initial... OK

python manage.py showmigrations catalogo
# Salida:
# catalogo
# [X] 0001_initial
python manage.py migrate
# Salida:
# No migrations to apply.
catalogo/models.py
# Cambio en el modelo: Producto gana el campo destacado.
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse


class Categoria(models.Model):
    nombre = models.CharField(max_length=60, unique=True)
    slug = models.SlugField(unique=True)

    class Meta:
        ordering = ["nombre"]

    def __str__(self):
        return self.nombre


class Producto(models.Model):
    categoria = models.ForeignKey(
        Categoria, on_delete=models.PROTECT, related_name="productos"
    )
    nombre = models.CharField(max_length=120)
    slug = models.SlugField(unique=True)
    precio = models.DecimalField(max_digits=8, decimal_places=2)
    stock = models.PositiveIntegerField(default=0)
    disponible = models.BooleanField(default=True)
    destacado = models.BooleanField(default=False)  # campo nuevo
    creado = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["nombre"]

    def __str__(self):
        return self.nombre

    def get_absolute_url(self):
        return reverse("catalogo:detalle", args=[self.slug])


class Resena(models.Model):
    producto = models.ForeignKey(
        Producto, on_delete=models.CASCADE, related_name="resenas"
    )
    autor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    calificacion = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)]
    )
    comentario = models.TextField(max_length=500)
    creada = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-creada"]

    def __str__(self):
        return f"{self.producto} ({self.calificacion})"
terminal
python manage.py makemigrations catalogo
# Salida:
# catalogo\migrations\0002_producto_destacado.py
# + Add field destacado to producto
python manage.py migrate catalogo
# Salida:
# Applying catalogo.0002_producto_destacado... OK
python manage.py showmigrations catalogo
# Salida:
# [X] 0001_initial
# [X] 0002_producto_destacado