Models and ORM
Defining database schemas, handling migrations, and querying the database.
🧑🏫 Sabse pehle — simple mein samjho#
Database mein SQL query (SELECT * FROM users) likhna kaafi boring aur error-prone kaam hai. Django ka ORM (Object-Relational Mapper) tumhein SQL bhula deta hai. Tum bas normal Python classes likhte ho (models.py mein) aur Django khud un classes ko padh kar database mein tables bana deta hai. Database me changes bhejne ki process ko Migrations kehte hain. Agar database se kuch dhoondhna hai, toh uske liye bhi Python functions (jaise objects.all()) use hote hain.
1. Defining Models#
A model is the single, definitive source of truth about your data. Each model maps to a single database table.
# blog/models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
# A character field requires a max_length
title = models.CharField(max_length=200)
# TextField for large amounts of text
content = models.TextField()
# Automatically set the date when the object is first created
created_at = models.DateTimeField(auto_now_add=True)
# Relationships: A Post belongs to a single User (ForeignKey = Many-to-One)
# on_delete=models.CASCADE means if the user is deleted, delete all their posts too!
author = models.ForeignKey(User, on_delete=models.CASCADE)
# This defines what string to print when this object is displayed in the Admin panel
def __str__(self):
return self.title
2. Migrations (Syncing with the Database)#
Whenever you create a new model or modify an existing one (like adding a new column), you must tell the database about it. This is a two-step process.
-
Generate the instructions:
python manage.py makemigrationsThis examines your
models.pyand creates a migration file (a python script containing the exact steps needed to change the database). -
Apply the instructions:
python manage.py migrateThis actually executes the SQL commands on your database (SQLite by default, but easily configurable to Postgres in
settings.py).
3. Querying the Database (The ORM API)#
Django attaches a special attribute called objects to every model. This is your "Manager" that handles all database queries.
# 1. Fetch ALL posts (Returns a QuerySet)
all_posts = Post.objects.all()
# 2. Fetch a SINGLE post (Throws an error if not found or if multiple match)
first_post = Post.objects.get(id=1)
# 3. FILTER posts (Returns a QuerySet of matching items)
# Double underscore '__' is Django's special syntax for lookups
taruns_posts = Post.objects.filter(author__username='tarun')
recent_posts = Post.objects.filter(created_at__year=2024)
# 4. CREATE a new post
new_post = Post.objects.create(title="Hello", content="World", author=my_user)
# OR
post2 = Post(title="Hello", content="World", author=my_user)
post2.save() # Manually save it
# 5. UPDATE an existing post
first_post.title = "Updated Title"
first_post.save()
# 6. DELETE a post
first_post.delete()
What is a QuerySet?#
Methods like all() and filter() return a QuerySet. QuerySets are lazy. This means they don't actually hit the database until you explicitly evaluate them (e.g., by looping over them in a template or printing them). You can chain filters together efficiently: Post.objects.filter(...).exclude(...).order_by('-created_at').