Django Tutorial menu

Django Models

A model is a Python class that describes one table in your database. Django creates the table for you.

The Database

A new project uses SQLite by default. The whole database is one file, db.sqlite3, so there is nothing to install. Later you can switch to PostgreSQL or MySQL by changing DATABASES in settings.py, without changing your models.

Your First Model

Edit courses/models.py:

Example

python
from django.db import models

class Course(models.Model):
    name = models.CharField(max_length=100)
    fee = models.PositiveIntegerField()
    duration_months = models.PositiveSmallIntegerField(default=3)
    is_online = models.BooleanField(default=False)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name
  • Each attribute becomes a column
  • Django adds an id column (the primary key) automatically
  • __str__ decides how a course is shown in the admin and the shell

Common Field Types

FieldStores
CharField(max_length=...)Short text, like a name
TextField()Long text
IntegerField() / PositiveIntegerField()Whole numbers
DecimalField(max_digits, decimal_places)Exact decimals, like money
BooleanField()True or False
DateField() / DateTimeField()Dates and times
EmailField()An email address
SlugField()URL-friendly text
ForeignKey(...)A link to another model

Useful options: default=..., blank=True (allowed empty in forms), null=True (allowed empty in the database), unique=True.

Migrations

Migrations turn your model changes into database changes. Run two commands:

Example

bash
python manage.py makemigrations
python manage.py migrate
Output
Migrations for 'courses':
  courses/migrations/0001_initial.py
    + Create model Course
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, courses, sessions
Running migrations:
  Applying courses.0001_initial... OK
CommandWhat it does
makemigrationsWrites a migration file describing your changes
migrateApplies all pending migrations to the database
showmigrationsLists migrations and whether they are applied

Run both commands every time you add, remove or change a model field.

Relationships

A student joins one course; a course has many students. Use ForeignKey:

Example

python
class Student(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="students")
    joined = models.DateField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} ({self.course})"

on_delete=models.CASCADE means: if a course is deleted, delete its students too. Other options are PROTECT (block the delete) and SET_NULL (needs null=True).

RelationshipFieldExample
Many to oneForeignKeyMany students, one course
Many to manyManyToManyFieldStudents and skills
One to oneOneToOneFieldA user and a profile

Trying Models in the Shell

Example

bash
python manage.py shell

Example

python
from courses.models import Course, Student

web = Course.objects.create(name="Web Development", fee=8000, duration_months=6)
Student.objects.create(name="Ali", email="ali@example.com", course=web)

print(web.students.count())
print(Student.objects.first())
Output
1
Ali (Web Development)

Exercise

Exercise

After adding a new field to a model, which two commands update the database?

Learn Django with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp