Django Lesson 3: Models & Database

🐍 Django CourseLesson 3 of 10 · 30% complete

Models define your database tables using Python classes. Django’s ORM handles SQL — you never write raw SQL for basic operations.

Define Models

# posts/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):
    STATUS = [('draft', 'Draft'), ('published', 'Published')]
    
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
    status = models.CharField(max_length=10, choices=STATUS, default='draft')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.title
    
    class Meta:
        ordering = ['-created_at']

Migrations & ORM

# Create migration files
python manage.py makemigrations

# Apply migrations (create tables)
python manage.py migrate

# Django ORM queries:
Post.objects.all()                          # all posts
Post.objects.filter(status="published")    # filter
Post.objects.get(slug="hello-world")       # single
Post.objects.create(title="New Post", ...) # create
post.save()                                # update
post.delete()                              # delete

🏋️ Practice Task

Create models for a task manager: Project (name, description, created_at) and Task (title, description, project ForeignKey, due_date, priority [low/medium/high], done [BooleanField]). Run migrations. Use the Django shell (python manage.py shell) to create 2 projects and 3 tasks.

💡 Hint: python manage.py shell. from posts.models import Project, Task. p = Project.objects.create(name=”Test”). Task.objects.create(title=”Fix bug”, project=p, priority=”high”)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *