Menu

Models and Databases

Introduction

Django's ORM (Object-Relational Mapping) lets you define your database schema using Python classes. No raw SQL needed for most operations.

Defining models

# models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    published = models.BooleanField(default=False)
    
    class Meta:
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title

# Migrations
# python manage.py makemigrations
# python manage.py migrate

# Using the ORM
Post.objects.all()                    # All posts
Post.objects.filter(published=True)    # Filtered
Post.objects.create(title="Hello", body="World", author=user)
post = Post.objects.get(id=1)
post.title = "Updated"
post.save()
post.delete()

Assignment

  1. Complete the Django tutorial Part 2 (models).
  2. Create models for a blog app with Post and Comment models.
  3. Practice querying with the Django shell: python manage.py shell

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!