Models and Database

In Django, Models define the structure of your database.
They allow you to create, read, update, and delete data using Python code instead of writing SQL directly.

Django uses an ORM (Object Relational Mapper), which means you interact with the database using Python classes.

What is a Model?

A Model is a Python class that represents a database table.

Each attribute in the model represents a column in the table.

Example:

from django.db import modelsclass Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True) def __str__(self):
return self.name

In this example:

  • Product is a table
  • name, price, stock, created_at are columns

Common Model Fields

CharField → Text with limited length
TextField → Large text
IntegerField → Whole numbers
DecimalField → Decimal numbers
FloatField → Floating point numbers
BooleanField → True or False
DateField → Date
DateTimeField → Date and time
EmailField → Email validation

Each field has options like:

  • max_length
  • default
  • null
  • blank
  • unique

How to Apply Models to Database

After creating or modifying models, run migrations.

Step 1: Create migration file

python manage.py makemigrations

Step 2: Apply migration

python manage.py migrate

This creates the database table automatically.

Database Configuration

Django uses SQLite by default.

In settings.py:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

You can also use:

  • PostgreSQL
  • MySQL
  • SQL Server

CRUD Operations Using Django ORM

Create Data

Product.objects.create(name="Laptop", price=80000, stock=10)

Read Data

Product.objects.all()
Product.objects.get(id=1)

Update Data

product = Product.objects.get(id=1)
product.price = 75000
product.save()

Delete Data

product = Product.objects.get(id=1)
product.delete()

Relationships Between Models

Django supports relationships:

ForeignKey → One-to-Many
ManyToManyField → Many-to-Many
OneToOneField → One-to-One

Example:

class Category(models.Model):
name = models.CharField(max_length=100)class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.CASCADE)

This connects Product to Category.

Django Admin Integration

To manage models in Admin:

from django.contrib import admin
from .models import Productadmin.site.register(Product)

Now you can manage data from the admin panel.

Why Models Are Important

Models help you:

Define data structure
Work with databases easily
Avoid writing complex SQL
Maintain clean code
Build scalable applications

Key Takeaway

Models are the foundation of database management in Django.
They define your data structure and allow you to interact with the database using Python instead of raw SQL, making development faster and more efficient.

Home » PYTHON FOR WEB DEVELOPMENT (PYWEB) > Django Framework > Models and Database