Django Include Models

Working with Django models and database

📦 What are Django Models?

Models are Python classes that define your database structure. Each model represents a database table, and each attribute represents a field. Django automatically creates database tables from your model definitions.


# models.py
from django.db import models

class Member(models.Model):
    firstname = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
                                    

Model Components

🏗️

Model Class

Define database table structure

class Member(models.Model):
📝

Fields

Define table columns and types

name = models.CharField()
🔗

Relationships

Connect models together

models.ForeignKey()
⚙️

Methods

Add custom functionality

def __str__(self):

🔹 Creating a Basic Model

Define your first model in the models.py file of your Django app. Models inherit from models.Model and use field types to specify what kind of data each column stores in the database.

# myapp/models.py
from django.db import models

class Member(models.Model):
    firstname = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    email = models.EmailField()
    phone = models.CharField(max_length=15)
    joined_date = models.DateField()
    
    def __str__(self):
        return f"{self.firstname} {self.lastname}"

🔹 Common Field Types

Django provides various field types for different data. Choose the appropriate field type based on what kind of information you need to store, ensuring data validation and proper database column types.

# myapp/models.py
from django.db import models

class Product(models.Model):
    # Text fields
    name = models.CharField(max_length=200)
    description = models.TextField()
    
    # Number fields
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.IntegerField()
    
    # Date/Time fields
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    # Boolean field
    is_active = models.BooleanField(default=True)
    
    # Email field
    contact_email = models.EmailField()

🔹 Making Migrations

After creating or modifying models, you must create and apply migrations to update your database schema. Migrations are Django's way of propagating model changes into your database structure safely and reversibly.

# Step 1: Create migration files
python manage.py makemigrations

# Output:
# Migrations for 'myapp':
#   myapp/migrations/0001_initial.py
#     - Create model Member

# Step 2: Apply migrations to database
python manage.py migrate

# Output:
# Running migrations:
#   Applying myapp.0001_initial... OK

🔹 Model Relationships

Connect models using relationships to represent real-world associations. Django supports one-to-many, many-to-many, and one-to-one relationships, allowing you to build complex data structures that mirror your application's domain logic.

# myapp/models.py
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    
    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=200)
    # ForeignKey: Many books can have one author
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    published_date = models.DateField()
    
    def __str__(self):
        return self.title

🔹 Importing Models in Views

To use models in your views, import them from the models module. This allows you to query, create, update, and delete database records through Django's ORM in your view functions.

# views.py
from django.shortcuts import render
from .models import Member, Product, Book

def member_list(request):
    # Get all members from database
    members = Member.objects.all()
    return render(request, 'members.html', {'members': members})

def member_detail(request, id):
    # Get specific member
    member = Member.objects.get(id=id)
    return render(request, 'member_detail.html', {'member': member})

🔹 Model Meta Options

Use the Meta class inside your model to configure additional options like table name, ordering, and verbose names. Meta options help you customize how Django handles your model without affecting the database fields.

# myapp/models.py
from django.db import models

class Member(models.Model):
    firstname = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    joined_date = models.DateField()
    
    class Meta:
        # Custom table name
        db_table = 'members'
        # Default ordering
        ordering = ['-joined_date']
        # Readable names
        verbose_name = 'Member'
        verbose_name_plural = 'Members'
    
    def __str__(self):
        return f"{self.firstname} {self.lastname}"

🧠 Test Your Knowledge

What command creates migration files for model changes?