Session Overview

  • Models Introduction
  • Creating First Model
  • Migrations
  • Django Admin Panel
  • Registering Models in Admin
  • Adding Data from Admin Panel

Models Introduction

A Model is a Python class used to represent a database table.

Django automatically creates database tables based on Model definitions.

Real World Example
Model Database Table
Category Category Table
Post Post Table
Comment Comment Table
Important: Every Model becomes a database table after running migrations.
Think Like This:
Model
   ↓
Migration
   ↓
Database Table
   ↓
Store Data

Creating First Model

We will create a Category model for our Blog Project.

File Location
demo/models.py
Create Category Model
from django.db import models

class Category(models.Model):

    Id = models.AutoField(primary_key=True)

    Name = models.CharField(max_length=100)
Understanding the Code
Code Purpose
models.Model Base class for all Models
Category Model Name
CharField Stores Text Data
max_length=100 Maximum 100 Characters
AutoField Auto Increment Primary Key
Primary Key

The Id field is the Primary Key of the Category table. AutoField automatically generates sequential values such as: 1, 2, 3, 4, ...

Note: Django automatically creates an Id field if we do not define one manually. In this training we are creating it explicitly so the table structure is easy to understand.

Migrations

Migrations are used to create or update database tables based on Model changes.

Whenever a Model is added or modified, migrations must be executed.

Step 1 - Create Migration File
python manage.py makemigrations
Output
Migrations for 'demo':

demo\migrations\0001_initial.py

+ Create model Category
Step 2 - Apply Migration
python manage.py migrate
Output
Applying demo.0001_initial... OK
Result: Django creates the Category table inside the database.
Important: During the first migration, Django creates several system tables automatically.
Examples
  • auth_user
  • auth_group
  • django_admin_log
  • django_session
  • django_content_type

These tables are required for Login, Admin Panel, Permissions and Session Management.

Default Table Naming Convention

Django automatically creates table names using:

AppName_ModelName
Example
App Name  : demo

Model Name : Category

Table Name : demo_category
Custom Table Name

We can specify our own table name using Meta class.

from django.db import models

class Category(models.Model):

    Id = models.AutoField(primary_key=True)

    Name = models.CharField(max_length=100)

    class Meta:

        db_table = 'Category'
Result
Category

Django will create the table with the exact name specified in db_table.

Remember:
Create Model
      ↓
makemigrations
      ↓
migrate
      ↓
Database Table Created
Missing any step will prevent the table from being created.
Viewing SQLite Database

Django uses SQLite by default and stores data in:

db.sqlite3

To view tables and data inside VS Code, install:

SQLite Viewer

After installation, open db.sqlite3 and browse tables directly from VS Code.

Django Admin Panel

Django provides a built-in Administration Panel for managing application data.

Administrators can add, edit and delete records without writing additional code.

Step 1 - Create Super User
python manage.py createsuperuser
Example
Username : admin

Email : admin@gmail.com

Password : ********
Step 2 - Start Server
python manage.py runserver
Step 3 - Open Admin Panel
http://127.0.0.1:8000/admin/
Result: Django displays the Admin Login page.
Why Admin Panel?
  • Add Records
  • Edit Records
  • Delete Records
  • Manage Website Data

Register Model in Admin

Creating a Model and running migrations creates the database table.

However, the Model will not appear in the Django Admin Panel until it is registered.

File Location
demo/admin.py
Register Category Model
from django.contrib import admin

from .models import Category

admin.site.register(Category)
Start Server
python manage.py runserver
Open Admin Panel
http://127.0.0.1:8000/admin/
Result: After login, the Category Model will appear in the Admin Panel.

Adding Data from Admin Panel

After registering the Model, records can be inserted directly from the Admin Panel.

Login To Admin Panel
http://127.0.0.1:8000/admin/
Open Category Section

Click on Category and then click the Add button.

Example Record
Id Name
1 Technology
2 Travel
3 Food
Database Table

The records entered through the Admin Panel are stored in the Category table.

Result: Data can now be added, updated and deleted without writing SQL queries.
Improving Display Name

By default, Django displays:

Category object (1)

To display the Category Name instead:

from django.db import models

class Category(models.Model):

    Id = models.AutoField(primary_key=True)

    Name = models.CharField(max_length=100)

    class Meta:
        db_table = 'Category'

    def __str__(self):
        return self.Name

Now the Admin Panel will display the actual Category Name.

Understanding __str__()

The __str__() method specifies what should be displayed when an object is converted to text.

Without __str__(), Django Admin displays:

Category object (1)

Category object (2)

After adding:

def __str__(self):
    return self.Name

Django Admin displays:

Technology

Travel

Food

In simple words, __str__() tells Django which field should be shown as the display name of the object.

Quick Revision

Models
  • Represents Table
  • Python Class
  • Stores Data Structure
Fields
  • AutoField
  • CharField
  • Primary Key
Migrations
  • makemigrations
  • migrate
  • Create Tables
Admin Panel
  • createsuperuser
  • Login
  • Manage Data
Model Registration
  • admin.py
  • site.register()
  • Visible In Admin
Useful Concepts
  • db_table
  • __str__()
  • SQLite Viewer
Important Commands
python manage.py makemigrations

python manage.py migrate

python manage.py createsuperuser

python manage.py runserver
Complete Flow
Create Model
      ↓
makemigrations
      ↓
migrate
      ↓
Register Model
      ↓
Admin Panel
      ↓
Add Records

Assignment

Complete the following tasks:
  1. Create a Model named Tag.
  2. Add the following fields:
    Id = models.AutoField(primary_key=True)
    
    Name = models.CharField(max_length=100)
  3. Configure a custom table name using:
    class Meta:
    
        db_table = 'Tag'
  4. Implement:
    def __str__(self):
        return self.Name
  5. Run migrations, register the Model in Admin Panel and add at least 3 records.
Company Logo
Full Stack Development Training - Python Django