Django Models
Every website needs to store data — student records, product details, blog posts, and more. In Django, you define how that data is stored using Models. A model is a Python class that represents a table in your database.
What is a Django Model?
A Model is a Python class that defines the structure of your data. Each class becomes a database table, and each attribute (variable) inside the class becomes a column in that table. You never write SQL queries directly — Django handles that for you.
Example: Think of a model like a form template in an office. The form has fixed fields — Name, Age, Address, and Phone. Every new person fills in the same form. Similarly, a Django model defines the fields (columns) that every record in your table must have.
Creating a Model
Open school/models.py and write your first model. Let us create a Student model:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
grade = models.CharField(max_length=10)
email = models.EmailField(unique=True)
enrolled_on = models.DateField(auto_now_add=True)
def __str__(self):
return self.name
This model will create a database table named school_student (Django auto-names it as appname_modelname) with the following columns: id (auto-created), name, age, grade, email, and enrolled_on.
Example: The Student class is like a student admission form. Every student who joins gets a new row in the database — their name, age, grade, and email fill the columns of that row, just like filling in boxes on a paper form.Common Field Types
Django provides many built-in field types for different kinds of data:
CharField(max_length=n)— Short text like names, titles. Always requires a max_length.TextField()— Long text like descriptions, articles, or paragraphs.IntegerField()— Whole numbers like age, quantity, or score.FloatField()— Decimal numbers like price or rating (e.g., 4.5).BooleanField()— True or False values like is_active or is_published.EmailField()— Email addresses. Django validates the format automatically.DateField()— Stores a date (year, month, day).DateTimeField()— Stores date and time together.ImageField()— Stores an uploaded image file path.ForeignKey()— Links two models together (relationship).
Field Options
Every field can have extra options to control its behavior:
null=True— The field can be empty in the database (stores NULL).blank=True— The field can be left empty in forms.default=value— Sets a default value if nothing is provided.unique=True— No two records can have the same value in this field.auto_now_add=True— Automatically saves the current date/time when a record is created.auto_now=True— Automatically updates the date/time every time the record is saved.
class Student(models.Model):
name = models.CharField(max_length=100)
phone = models.CharField(max_length=15, blank=True, null=True)
is_active = models.BooleanField(default=True)
joined_date = models.DateField(auto_now_add=True)
The __str__ Method
The __str__ method tells Django what to display when a model object is shown — for example, in the admin panel or in a print statement. Without it, Django shows something unhelpful like "Student object (1)".
def __str__(self):
return self.name
Example: Without __str__, your admin panel shows "Student object (1), Student object (2)". With it, it shows "Rahul", "Priya" — which is much more useful when managing records.Model Relationships
Real-world data is connected. A student belongs to a class. A class has many students. Django handles these connections using relationship fields.
ForeignKey — Many to One
Many students can belong to one class. This is a Many-to-One relationship:
class Classroom(models.Model):
room_number = models.CharField(max_length=10)
floor = models.IntegerField()
def __str__(self):
return self.room_number
class Student(models.Model):
name = models.CharField(max_length=100)
classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE)
def __str__(self):
return self.name
on_delete=models.CASCADE means: if a classroom is deleted, all students in that classroom are also deleted automatically.
Example: A teacher (one) has many students (many). If the teacher's record is deleted, you can choose to automatically remove all their students too, or just leave those students unassigned.
ManyToManyField — Many to Many
A student can enroll in many subjects, and a subject can have many students:
class Subject(models.Model):
name = models.CharField(max_length=100)
students = models.ManyToManyField(Student)
def __str__(self):
return self.name
OneToOneField — One to One
Each student has exactly one student ID card:
class IDCard(models.Model):
student = models.OneToOneField(Student, on_delete=models.CASCADE)
card_number = models.CharField(max_length=20)
The Meta Class — Extra Model Options
Inside a model, you can add a Meta class to define extra behavior like default sorting and table naming:
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Meta:
ordering = ['name'] # Sort by name alphabetically
verbose_name = 'Student' # Display name in admin
verbose_name_plural = 'Students'
def __str__(self):
return self.name
Quick Recap
# school/models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField(unique=True)
is_active = models.BooleanField(default=True)
joined_date = models.DateField(auto_now_add=True)
def __str__(self):
return self.name
After creating or editing models, you must always run migrations to apply the changes to your database. We will cover this in the next lesson.
