← Back to Chapters

Defining Models in models.py

? Defining Models in models.py

? Quick Overview

In Django, models define the structure of your database tables. They are Python classes that inherit from django.db.models.Model. Each model represents a table, and each attribute represents a column.

? Key Concepts

  • Each model maps to a database table
  • Each field maps to a table column
  • Models handle data structure and behavior
  • Relationships are defined using special field types

? Syntax / Theory

Models are created inside the models.py file of a Django app. You define a class that inherits from models.Model and add fields using Django’s built-in field types.

? Example: Simple Model

? View Code Example
# Import Django model base class
from django.db import models

# Define a Book model
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    publish_date = models.DateField()
    isbn_number = models.CharField(max_length=13)

# String representation of the model
def __str__(self):
    return self.title

? Field Types in Django Models

  • CharField – short text
  • IntegerField – whole numbers
  • DateField – dates
  • TextField – long text
  • DecimalField – precise numeric values
  • BooleanField – True / False
  • ForeignKey – relationships

? Example: Multiple Field Types

? View Code Example
# Product model demonstrating multiple field types
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available = models.BooleanField(default=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE)

# Return product name when printed
def __str__(self):
    return self.name

? Live Output / Explanation

? What Happens?

Each model becomes a database table after running migrations. Django automatically generates SQL based on your model definitions.

? Interactive Model Playground

Step 1: Define your Model Fields

? Interactive Model Flow

Model ➜ Migration ➜ Database Table

Try modifying a field, run makemigrations, then migrate to see schema updates.

? Use Cases

  • User profiles
  • E-commerce products
  • Blog posts and comments
  • School or employee records

✅ Tips & Best Practices

  • Choose correct field types
  • Use __str__ for readability
  • Normalize data using relationships
  • Run migrations after every model change

? Try It Yourself

  • Create two related models using ForeignKey
  • Add them to Django admin
  • Test CRUD operations