Learn Django · 5/13

Models: Your Database Blueprint 🗄️

8 min read

Building a web application without a database is like opening a library with no books. You can have a beautiful building, but there is nothing to actually read, store, or borrow. In Django, the way we handle this data storage is through Models.

Let us learn how Django handles databases, how we define our data, and how we interact with it seamlessly.


1. Introduction to the Django ORM (Object-Relational Mapper)

Definition:
An Object-Relational Mapper (ORM) is a piece of software that automatically converts data between incompatible systems—specifically, between Python objects (code) and relational databases (SQL tables).

The Problem:
Imagine you are building an application. To get a list of users from the database, you would traditionally have to write raw SQL: SELECT * FROM users WHERE active = 1;.
Writing raw SQL inside Python code is problematic for a few reasons:

  1. It is prone to syntax errors (missing a single comma can crash your app).
  2. It opens the door to SQL injection attacks if you do not perfectly sanitize user input.
  3. It locks you into a specific database provider. If you write raw PostgreSQL queries today and your boss tells you to switch to MySQL tomorrow, you have to rewrite thousands of lines of code.

The Solution:
The Django ORM solves this by allowing you to write purely in Python. You define Python classes, and the ORM translates them into secure, optimized SQL behind the scenes. If you ever switch databases, you change one line in your configuration file, and the ORM handles the rest. No SQL rewrites required.

How it Works Under the Hood

When you ask Django to fetch data, you write Python code like this:

python
active_users = User.objects.filter(is_active=True)

The ORM acts as an invisible translator. It reads your Python code, determines which database you are currently connected to (SQLite, PostgreSQL, MySQL), and dynamically generates the exact SQL string needed: SELECT * FROM auth_user WHERE is_active = True;.


2. Defining Models: Choosing the Right Fields

Definition:
A Model is a standard Python class that inherits from django.db.models.Model. Each model maps exactly to a single database table. Each attribute (variable) inside that class represents a database column.

The Problem:
Databases are extremely strict. If you tell a database that a column should hold a number, and you accidentally try to save the word "banana" into it, the database will throw a massive error and halt your application. You need a way to strictly define what type of data is allowed in each column, how long it can be, and whether it can be left blank.

The Solution:
Django provides Fields. Fields define the data type (e.g., text, integer, date) and the constraints (e.g., maximum length, unique values) for your database columns. By choosing the right fields in your Model, Django enforces these rules before the data ever reaches the database.

Industry Standard: The Most Common Fields

There are dozens of field types in Django, but in the real world, you will use these 5 types 90% of the time. We will build an E-commerce Product model to see them in action.

python
# models.py
from django.db import models

class Product(models.Model):
    # 1. CharField: For short strings. Requires a max_length.
    name = models.CharField(max_length=255)
    
    # 2. TextField: For unlimited text. Used for descriptions, blog posts, etc.
    description = models.TextField(blank=True, null=True) 
    
    # 3. DecimalField: Industry standard for MONEY. Never use FloatField for money!
    price = models.DecimalField(max_digits=10, decimal_places=2)
    
    # 4. BooleanField: True or False. Good for flags.
    is_in_stock = models.BooleanField(default=True)
    
    # 5. DateTimeField: Tracks dates and times. 
    # auto_now_add=True automatically sets the time when the object is created.
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Understanding null vs blank (A Frequent Industry Stumbling Block)

Notice description = models.TextField(blank=True, null=True). What does this mean?

  • null=True: Tells the database it is okay to leave this column empty (store it as NULL).
  • blank=True: Tells Django forms and validation that it is okay for a user to submit this field empty.

Rule of Thumb: Use both if you want an optional text field. If you only use null=True, Django's admin panel will still force you to type something into the box.

Relationships: Connecting Models

In the real world, data is connected. A Product belongs to a Category. We connect them using a ForeignKey.
Imagine a real-life filing cabinet. A ForeignKey is simply a piece of paper in the Product folder that says, "For category details, go look at folder #4 in the Category cabinet."

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

class Product(models.Model):
    # ... previous fields ...
    # Connects this product to a Category. 
    # on_delete=models.CASCADE means if the Category is deleted, delete all its products too.
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')

3. Migrations: Translating Code to Database Tables

Definition:
Migrations are Django’s way of keeping track of changes you make to your models. They are version control systems for your database schema.

The Problem:
You just wrote the Product class in Python. However, your database is completely unaware of this. It has no tables, no columns, and no rules. If you run your application right now, it will crash because the database structure does not match the code structure. Furthermore, if you decide later to add a "discount" column to a database that already has 10,000 products, how do you do that without deleting all the existing data?

The Solution:
Migrations safely apply your Python code changes to the database. Django generates step-by-step SQL instructions (the migration files) and executes them against the database without destroying existing data.

The Two Commands You Will Run Thousands of Times

  1. python manage.py makemigrations (Drafting the Blueprint)
    When you run this, Django looks at your models.py files, notices any changes, and writes a set of instructions (a migration file) on how to update the database. It does not touch the database yet. It just prepares the plan.

  2. python manage.py migrate (Building the House)
    When you run this, Django connects to your database, looks at the instructions generated by makemigrations, and converts them into SQL. It then executes the SQL to create or alter your tables.

A Frequent Real-World Problem: The "No Default" Error

Imagine you have an app running in production with 500 users. You decide to add a date_of_birth field to your User model:

python
date_of_birth = models.DateField()

When you run makemigrations, Django will panic and give you a warning:
"You are trying to add a non-nullable field 'date_of_birth' to user without a default; we can't do that (the database needs something to populate existing rows)."

Django is asking: "What should I put in this new column for the 500 users that already exist?"
The Fix: Always provide a default value when adding new fields to existing models, or set null=True, blank=True.


4. The Django Admin: Setting up the Free Out-of-the-Box Dashboard

Definition:
The Django Admin is a built-in, web-based graphical user interface (GUI) that allows authorized users to perform CRUD (Create, Read, Update, Delete) operations on the database models.

The Problem:
You have built your models and migrated them to the database. Now you want to add some sample categories and products to test your application. To do this, you would normally have to build an HTML form, write a view to process the form, write routing logic, and handle error validation. Doing this just to add test data or manage internal settings takes days of tedious work.

The Solution:
Django automatically generates a fully functional, secure administration dashboard for you based entirely on the fields you defined in your models.

Step 1: Create a Superuser

To access the admin panel, you need an account with supreme administrative privileges. Open your terminal and run:

bash
python manage.py createsuperuser

Follow the prompts to set up an email, username, and password. (Don't panic when you type your password and nothing shows up on the screen; the terminal hides it for security).

Step 2: Registering Models the Industry Way

By default, the Admin panel only knows about Django's internal tables (like Users and Groups). You have to explicitly tell it to manage your new models. We do this in the admin.py file using decorators.

python
# admin.py
from django.contrib import admin
from .models import Product, Category

# Simple registration
admin.site.register(Category)

# Industry standard: Advanced registration using decorators
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    # Determine which columns show up in the main list view
    list_display = ('name', 'price', 'is_in_stock', 'created_at')
    
    # Add a search bar to search by product name
    search_fields = ('name',)
    
    # Add a filter sidebar
    list_filter = ('is_in_stock', 'category')

Why use the @admin.register decorator?

While admin.site.register() works, using the decorator (@admin.register) alongside a ModelAdmin class allows you to drastically customize the user experience.

Imagine handing your application over to a client. If their product catalog grows to 5,000 items, they will need search bars, filters, and clean tables. The 5 lines of code above automatically generate a search box, a right-hand filtering sidebar, and a neatly organized table, saving you weeks of front-end development.


References and Further Reading

To dive deeper into the exact syntax and advanced use cases, consult the official Django documentation:

Challenge

You are building the backend for an e-commerce platform. Your task is to define the database schema using Django models and configure the admin interface for one of the models.

Requirements:

  1. Category Model:

    • name: A character field with a maximum length of 100 characters. It must be unique.
    • description: A text field that can be left blank.
  2. Product Model:

    • name: A character field with a maximum length of 255 characters.
    • description: A text field.
    • price: A decimal field suitable for currency, with a maximum of 10 digits and 2 decimal places.
    • is_available: A boolean field that defaults to True.
    • created_at: A datetime field that automatically records the creation timestamp and cannot be edited later.
    • category: A foreign key relationship to the Category model. If a category is deleted, all products within it should also be deleted.
  3. ProductAdmin Configuration:

    • Create a ModelAdmin class for the Product model.
    • Use the @admin.register() decorator to register it.
    • Configure the admin list view to display the product's name, category, price, and is_available status.
    • Add a search bar that allows searching by the product's name and description.
    • Add sidebar filters for the is_available status and the category.

Expected result

Your final code should consist of two model classes, Category and Product, and one ModelAdmin class, ProductAdmin.

Category Model:

  • A CharField named name with max_length=100 and unique=True.
  • A TextField named description with blank=True.

Product Model:

  • A CharField named name with max_length=255.
  • A TextField named description.
  • A DecimalField named price with max_digits=10 and decimal_places=2.
  • A BooleanField named is_available with default=True.
  • A DateTimeField named created_at with auto_now_add=True.
  • A ForeignKey field named category pointing to the Category model, with on_delete=models.CASCADE.

ProductAdmin Class:

  • The class should be decorated with @admin.register(Product).
  • It must inherit from admin.ModelAdmin.
  • It should define list_display as ('name', 'category', 'price', 'is_available').
  • It should define search_fields as ('name', 'description').
  • It should define list_filter as ('is_available', 'category').
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.