Menu

Django & Flask Topic

1. What is a Django Model?

A Model is a single, definitive source of information about your data. It's a Python class that subclasses django.db.models.Model.

  • Each model represents a database table.

  • Each attribute of the model represents a database field (a column in the table).

  • Each instance of the model represents a row in the table.

What is the Django ORM?

The ORM (Object-Relational Mapper) is the magic behind the scenes. It's a powerful component of Django that acts as a bridge between your Python code and your database.

  • It lets you query your database using Python code instead of SQL.

  • It handles the translation, so you can work with data as Python objects.


2. Key Concepts in Action

Let's build the blog example.

Creating Model Classes

You define models in the models.py file of your Django app.

python

# myblog/models.py
from django.db import models

class Author(models.Model):
    # This creates a VARCHAR column in the database.
    name = models.CharField(max_length=100)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class BlogPost(models.Model):
    # CharField is for short-to-medium text, like a title.
    title = models.CharField(max_length=200)
    
    # TextField is for large, unlimited text, like the body of a post.
    content = models.TextField()
    
    # DateTimeField automatically sets the date when the object is first created.
    published_date = models.DateTimeField(auto_now_add=True)
    
    # ForeignKey defines a "many-to-one" relationship.
    # One Author can have many BlogPosts.
    # on_delete=models.CASCADE means if the Author is deleted, their posts are too.
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    
    # ManyToManyField defines a "many-to-many" relationship.
    # A BlogPost can have many Categories, and a Category can be in many BlogPosts.
    categories = models.ManyToManyField(Category)

    def __str__(self):
        return self.title

Field Types (A Small Sample)

  • CharField: For short strings. Requires max_length.

  • TextField: For large amounts of text.

  • IntegerField, BooleanField: For integers and True/False values.

  • DateField, DateTimeField: For dates and timestamps.

  • EmailField, URLField: Specialized CharFields with built-in validation.

  • ForeignKey: A link to another Model (a "many-to-one" relationship).

  • ManyToManyField: A link to another Model for "many-to-many" relationships.

Running Makemigrations and Migrate

This is a critical two-step process to create the actual database tables from your Python models.

  1. makemigrations: This command looks at your models.py, detects any changes you've made to your models, and generates a "migration" file. A migration is a Python script that describes how to adjust the database schema (e.g., create a new table, add a column).

    bash

    python manage.py makemigrations

    Output: Migrations for 'myblog': myblog/migrations/0001_initial.py ...

  2. migrate: This command takes all the migration files and applies them to your database, running the SQL commands (like CREATE TABLE) to bring the database structure in line with your models.

    bash

    python manage.py migrate

    Output: Applying myblog.0001_initial... OK

Think of it like this: makemigrations is the staging step (packing the instructions), and migrate is the deployment step (executing the instructions).


3. Basic Queries using the ORM

You interact with your data using the model's default manager, which is objects.

Let's play with our BlogPost model in the Django shell (python manage.py shell).

Create (Saving Data)

python

# First, create an Author object and save it
author_john = Author(name="John Doe", email="john@example.com")
author_john.save() # This performs the INSERT SQL

# A quicker way to create and save in one step
author_jane = Author.objects.create(name="Jane Smith", email="jane@example.com")

# Create a category
tech_category = Category.objects.create(name="Technology")

# Now, create a BlogPost
post = BlogPost(
    title="My First Post",
    content="This is the amazing content of my first blog post!",
    author=author_john # Assign the Author object we created
)
post.save()
# Now, add the category (this works because it's a ManyToManyField)
post.categories.add(tech_category)

Read (Querying Data)

This is where the ORM shines.

  • Get all objects: objects.all()

    python

    all_posts = BlogPost.objects.all()
    # This is equivalent to: SELECT * FROM myblog_blogpost;
    for post in all_posts:
        print(post.title)

     

  • Get a single object by a condition: objects.get()

    python

    # Gets the one and only post with this exact title.
    # Throws an error if zero or multiple posts are found.
    first_post = BlogPost.objects.get(title="My First Post")
    print(first_post.content)

     

  • Filter objects (get a subset): objects.filter()

    python

    # Gets all posts where the title contains the word "First"
    filtered_posts = BlogPost.objects.filter(title__contains="First")
    # The double-underscore (__) is used for "lookups" (like contains, startswith, etc.)
    
    # Gets all posts written by the author_john object
    johns_posts = BlogPost.objects.filter(author=author_john)
    
    # You can chain filters
    recent_johns_posts = BlogPost.objects.filter(
        author=author_john, 
        published_date__year=2023
    )

     

Update (Modifying Data)

python

# 1. Get the object
post = BlogPost.objects.get(title="My First Post")

# 2. Modify its attributes
post.title = "My Updated First Post"

# 3. Save it again (this performs an UPDATE SQL)
post.save()

Delete (Removing Data)

python

# 1. Get the object
post = BlogPost.objects.get(title="My Updated First Post")

# 2. Delete it
post.delete()

Summary

Concept What it is Analogy
Model A Python class representing a database table. A blueprint for a house.
Field An attribute on a Model, representing a table column. A room in the blueprint (e.g., bedroom, kitchen).
ORM The system that translates Python to SQL and back. A universal translator.
Migration A script that updates the database schema. Instructions for construction workers to modify the house.
objects.all() A query to get all rows from a table. "Get me all the houses."
objects.get() A query to get one specific row. "Get me the house at 123 Main St."
objects.filter() A query to get a subset of rows. "Get me all the blue houses."

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?