Lesson 24 of 60 – Django Models
40%

Django Models

Django models are used to define the structure of data that an application works with. A model is a Python class that usually represents a database table. Each model field represents a type of data stored in that table.

Note: Django models work with the Django ORM, which allows you to work with database data using Python instead of writing SQL for every operation.

1. What is a Django Model?

A Django model is a Python class used to describe data that an application needs to store and manage.

For example, a student model may contain:

  • Student name
  • Email address
  • Mobile number
  • Course
  • Date of admission

2. Models and Database Tables

Django normally maps a model to a database table.

Student Model
      ↓
students_student Table

The model defines the structure, while the database stores the actual records.

3. Where Are Models Defined?

Models are normally defined inside the app's models.py file.

students/
├── models.py
├── views.py
├── admin.py
└── apps.py

Open models.py to create your application's models.

4. Import the models Module

A basic Django model starts by importing Django's models module.

from django.db import models

The models module provides classes such as CharField, IntegerField, and DateField.

5. Creating a Simple Model

A model is created by defining a Python class that inherits from models.Model.

from django.db import models

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

Here, Student is the model name and name is a model field.

6. Model Class

The class represents the model.

class Student(models.Model):
    pass

By inheriting from models.Model, the class becomes a Django model.

7. Model Fields

Fields define the type of information that the model stores.

class Student(models.Model):

    name = models.CharField(max_length=100)

    age = models.IntegerField()

    email = models.EmailField()

Each field becomes a column in the corresponding database table.

8. CharField

CharField is commonly used for short text.

name = models.CharField(max_length=100)

The max_length argument defines the maximum length of the text.

Examples:

name = models.CharField(max_length=100)

city = models.CharField(max_length=50)

course = models.CharField(max_length=100)

9. IntegerField

IntegerField stores integer values.

age = models.IntegerField()

marks = models.IntegerField()

quantity = models.IntegerField()

It is useful for values such as age, quantity, and marks.

10. EmailField

EmailField is designed for email addresses and provides email validation behavior.

email = models.EmailField()

Example value:

student@example.com

11. BooleanField

BooleanField stores a true or false value.

is_active = models.BooleanField(default=True)

It can be useful for status values such as active/inactive.

12. DateField

DateField is used for date values.

admission_date = models.DateField()

It can store values representing dates such as admission dates or birthdays.

13. DateTimeField

DateTimeField is used when both date and time are needed.

created_at = models.DateTimeField(
    auto_now_add=True
)

This is commonly used for timestamps.

14. TextField

TextField is commonly used for larger amounts of text.

description = models.TextField()

It can be used for descriptions, comments, articles, or other long text.

15. DecimalField

DecimalField is useful for decimal values such as prices or fees.

fee = models.DecimalField(
    max_digits=10,
    decimal_places=2
)

Here, max_digits represents the total number of digits and decimal_places represents digits after the decimal point.

16. Default Values

A field can have a default value.

is_active = models.BooleanField(
    default=True
)

If a value is not supplied when creating a record, Django can use the default value.

17. null and blank

The null option controls whether the database can store NULL for a field. The blank option is related to validation and whether an empty value is allowed by forms.

phone = models.CharField(
    max_length=15,
    blank=True
)

These options have different purposes and should not be treated as identical.

18. Primary Key

Django automatically creates an ID field as the primary key when a model does not explicitly define one.

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

The generated primary key uniquely identifies each database record.

19. Custom Primary Key

A model can explicitly define a field as the primary key.

student_id = models.CharField(
    max_length=20,
    primary_key=True
)

Only one field can be the primary key of a model.

20. Creating a Complete Student Model

from django.db import models

class Student(models.Model):

    name = models.CharField(
        max_length=100
    )

    email = models.EmailField()

    mobile = models.CharField(
        max_length=15
    )

    age = models.IntegerField()

    course = models.CharField(
        max_length=100
    )

    is_active = models.BooleanField(
        default=True
    )

This model contains several fields for storing student information.

21. Model Metadata

Django models can contain an inner Meta class to configure additional model options.

class Student(models.Model):

    name = models.CharField(
        max_length=100
    )

    class Meta:
        ordering = ['name']

The Meta class can control various model-level options.

22. String Representation of a Model

The __str__() method can define how a model object is represented as text.

class Student(models.Model):

    name = models.CharField(
        max_length=100
    )

    def __str__(self):
        return self.name

This is especially useful when viewing objects in the Django admin interface.

23. Create Migrations

After creating or changing a model, use makemigrations to create migration files.

python manage.py makemigrations

Django examines model changes and creates migration instructions.

24. Apply Migrations

Use the migrate command to apply migrations to the database.

python manage.py migrate

This updates the database according to the migration files.

25. Model and Django ORM

Django's Object-Relational Mapper, commonly called the ORM, allows Python code to work with database records.

For example:

Student.objects.all()

This can be used to retrieve Student records without writing a raw SQL query for this basic operation.

26. Creating a Model Object

A model object can be created using Python code.

student = Student(
    name="Rahul",
    email="rahul@example.com",
    age=20
)

student.save()

The save() method stores the object in the database.

27. Reading Model Records

The ORM provides QuerySets for retrieving model records.

students = Student.objects.all()

The returned QuerySet can contain multiple Student objects.

A single record can also be retrieved with appropriate ORM methods such as get().

28. Model in Django Admin

Models can be registered in admin.py so that administrators can manage records through Django's admin interface.

from django.contrib import admin
from .models import Student

admin.site.register(Student)

After registration and login, the model can be available in the admin site.

29. Complete Model Workflow

Step 1: Define the model

from django.db import models

class Student(models.Model):

    name = models.CharField(
        max_length=100
    )

    email = models.EmailField()

    age = models.IntegerField()

    def __str__(self):
        return self.name

Step 2: Create migrations

python manage.py makemigrations

Step 3: Apply migrations

python manage.py migrate

Step 4: Register the model

from django.contrib import admin
from .models import Student

admin.site.register(Student)

The model is now connected to Django's database and admin workflow.

30. Summary of Django Models

Django models provide a convenient way to define and manage application data. They are Python classes that work with Django's ORM and database system.

  • Models are normally defined in models.py.
  • A model inherits from models.Model.
  • Model fields represent database columns.
  • CharField stores text.
  • IntegerField stores integer values.
  • EmailField stores email-related values.
  • DateField stores dates.
  • DateTimeField stores dates and times.
  • BooleanField stores true or false values.
  • Use makemigrations and migrate after model changes.
  • Django ORM allows Python code to work with database records.

📌 Key Points

  • A Django model is a Python class that represents application data.
  • Models are normally created inside models.py.
  • Model fields define the type of stored data.
  • Django automatically provides a primary key when one is not explicitly defined.
  • The __str__() method provides a useful text representation of objects.
  • makemigrations creates migration files.
  • migrate applies migrations to the database.
  • Django ORM allows database operations using Python.
  • Models can be registered in the Django admin site.

🧠 Quick Quiz

Question: Which file is normally used to define Django models?