Django Models


Details

In Django, a model is the way you define a database table using Python code. Models make it simple to create, update, and manage structured data without writing raw SQL queries.


What Is a Django Model?

Earlier, your website only showed hard-coded results or HTML layouts. Now it’s time to work with stored information using Django’s model system.

A model acts like a blueprint for your database tables. Every field in the model corresponds to a column in the table.


Creating a Data Model

Navigate to the models.py file inside the members/ folder.

Inside it, define a class called Member like this:

from django.db import models  

class Member(models.Model):     
       firstname = models.CharField(max_length=255)     
      Lastname = models.CharField(max_length=255) 
  • firstname and lastname will both hold character-based values.
  • The CharField type limits each input to a maximum of 255 characters.

Where Is the Database?

By default, Django sets up a lightweight SQLite file (db.sqlite3) inside your project root (my_tennis_club/). This is where all your model-based data will be stored unless configured otherwise.


Make Migration Scripts

To convert your model code into a migration (a set of changes Django uses to modify the database), use this command:

python manage.py makemigrations members

Expected OutPut:

Migrations for 'members':   
    members/migrations/0001_initial.py     
        - Create model Member 

This means Django has prepared the structure changes but hasn't applied them yet.


What Gets Created?

Django places a Python file inside the migrations/ folder of your app. It tracks how your tables are structured.

Contents of the generated file may look like:

from django.db import migrations, models  

class Migration(migrations.Migration):      

        initial = True      

       dependencies = []      

       operations = [         
            migrations.CreateModel(             
                  name='Member',             
                  fields=[                 
                         ('id', models.BigAutoField(primary_key=True, serialize=False)),                
                         ('firstname', models.CharField(max_length=255)),                
                         ('lastname', models.CharField(max_length=255)),             
                 ],         
          ),     
] 

Django automatically inserts an id column as the primary key, incrementing for each new entry. You can specify a custom one if needed.


Apply the Migration to the Database

Once the migration is ready, apply it:

python manage.py migrate

This will create the actual table in your database. Example output:

Operations to perform:   
      Apply all migrations: admin, auth, contenttypes, members, sessions 
Running migrations:   
     Applying members.0001_initial... OK 

Now your data structure exists inside the database file!


Check the SQL Commands

You can see the exact SQL Django used behind the scenes by running:

python manage.py sqlmigrate members 0001

Which will show something like:

BEGIN; 
CREATE TABLE "members_member" (   
     "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,   
     "firstname" varchar(255) NOT NULL,   
     "lastname" varchar(255) NOT NULL
); 
COMMIT;

Recap

  • Models define tables using Python classes
  • Fields describe what kind of data is stored
  • Migrations convert your code into SQL
  • Django manages everything behind the scenes

Prefer Learning by Watching?

Watch these YouTube tutorials to understand HTML Tutorial visually:

What You'll Learn:
  • 📌 Python Django Models and Migrations
  • 📌 #17 Django tutorials | Models and Migrations
Previous Next