Models, Fields & Migrations
Models are Python classes that describe the tables and database fields of your application. Migrations are Django's way of propagating changes you make to your models into your database schema.
1 Defining a Model
Python — models.py
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
2 Migration Lifecycle
Shell — Terminal Commands
# Detect changes in models.py and create migration files
python manage.py makemigrations
# Inspect the raw SQL that a migration will execute
python manage.py sqlmigrate blog 0001
# Run the migrations and update database schema
python manage.py migrate
3 Code Challenge
Challenge: Add a new field named
views_count (integer field, defaults to 0) to the Post model, generate the migration file, and apply it to your database.