๐ Introduction
In Django, a model is used to define the structure of data stored in the database.
A model represents a database table, and each attribute in the model represents a column in that table.
In this program, we will:
- create a
Studentmodel - define its fields
- register the app
- apply migrations
- generate the database table
This is the first and most important step in Django database programming.
๐ฏ Program Statement
๐ Create a Student model and apply migrations to generate database table.
๐ง Concept
This program introduces:
models.py- model fields
makemigrationsmigrate
โ๏ธ Step 1: Create the App
If the app is not already created, run:
python manage.py startapp myapp
โ๏ธ Step 2: Register App in settings.py
๐ File: settings.py
๐น Path:
myproject/myproject/settings.py
๐น Code:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
๐ง Explanation
- Django must know that
myappis part of the project - If the app is not added to
INSTALLED_APPS, migrations will not work properly for that app
โ๏ธ Step 3: Create Student Model
๐ File: models.py
๐น Path:
myproject/myapp/models.py
๐น Code:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
course = models.CharField(max_length=100)
email = models.EmailField(unique=True)
def __str__(self):
return self.name
๐ง Explanation
We created a model named Student with 4 fields:
nameโ stores student nameageโ stores agecourseโ stores course nameemailโ stores email address
Field Types Used
CharFieldโ for text valuesIntegerFieldโ for whole numbersEmailFieldโ for email addresses
unique=True
This ensures that no two students can have the same email address.
__str__() method
This defines how the object will appear in admin panel and shell output.
Instead of showing Student object (1), Django will display the student’s name.
โ๏ธ Step 4: Create Migration File
Run this command:
python manage.py makemigrations
โ Example Output:
Migrations for 'myapp':
myapp/migrations/0001_initial.py
+ Create model Student
๐ง Explanation
makemigrationschecks changes inmodels.py- It creates a migration file describing what changes should be made in the database
โ๏ธ Step 5: Apply Migration to Database
Run this command:
python manage.py migrate
โ Example Output:
Applying myapp.0001_initial... OK
๐ง Explanation
migrateactually creates the table in the database- After this command, a
Studenttable is generated
โ๏ธ Step 6: Database Table Generated
After migration, Django creates a database table for the model.
If you are using the default SQLite database, the data will be stored in:
๐ File: db.sqlite3
๐น Path:
myproject/db.sqlite3
๐ง Table Name Note
By default, Django creates the table name as:
myapp_student
Format:
appname_modelname
โ๏ธ Step 7: Optional โ Verify in Admin or Database Browser
You can verify that the table was created by:
- opening SQLite database in DB Browser for SQLite
- checking Django admin later
- using Django shell in the next post
๐ Output / Result
After running migrations successfully:
- Migration file is created in
myapp/migrations/ - Student table is created in database
๐ง How It Works
- We define the model in
models.py - Django reads the model structure
makemigrationscreates migration instructionsmigrateapplies those instructions to database- Database table is generated
๐ฅ Key Concepts
Model Class
class Student(models.Model):
A model must inherit from models.Model.
Character Field
name = models.CharField(max_length=100)
Stores text with maximum length.
Integer Field
age = models.IntegerField()
Stores numeric integer values.
Email Field
email = models.EmailField(unique=True)
Stores email and enforces uniqueness.
Migration Command
python manage.py makemigrations
Creates migration file.
Apply Command
python manage.py migrate
Creates table in the database.
โ ๏ธ Common Errors
โ App not added in INSTALLED_APPS
If myapp is missing in settings.py, Django may not detect the model correctly.
โ Forgot to run makemigrations
If you directly run migrate without creating migrations, the model changes may not be applied.
โ Migration created but not applied
makemigrations only creates migration files.
You must also run:
python manage.py migrate
โ Indentation error in models.py
Python is indentation-sensitive, so class and methods must be aligned properly.
โ Missing __str__() method
The model will still work, but object representation in admin will not be user-friendly.
๐งช Practice Questions
- Add one more field called
city - Add a field
marks - Create another model called
Teacher - Change
coursemax length from 100 to 50 - Add
phonefield withCharField
๐ค Viva Questions & Answers
1. What is a model in Django?
A model is a Python class that represents a database table. It defines the structure of data stored in the database.
2. What is the purpose of models.py?
models.py is used to define the database schema in Django. Each model class inside it corresponds to a database table.
3. Why does a model inherit from models.Model?
A Django model must inherit from models.Model so that Django can provide database-related functionality such as table creation and querying.
4. What is CharField in Django models?
CharField is used to store text values of limited length. It requires the max_length argument.
5. What is the use of EmailField?
EmailField is used to store email addresses and provides email-specific validation.
6. What does unique=True do?
It ensures that no duplicate values are allowed in that field across records in the table.
7. What is the purpose of __str__() method in a model?
The __str__() method returns a readable string representation of the object. It is useful in admin panel and shell.
8. What is the difference between makemigrations and migrate?
makemigrations creates migration files based on model changes, while migrate applies those changes to the database.
9. What is a migration in Django?
A migration is a file that keeps track of changes made to models and tells Django how to update the database.
10. Why are migrations important?
Migrations keep the database structure synchronized with the models. They allow safe and systematic schema changes.
๐ Next Post: Insert Records into the Database using Django Shell or Admin Panel
๐ Back to List: Django Programs (60 Questions with Solutions)
Further Reading
Introduction to Django Framework and its Features
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
