Using Django ORM to Interact with Databases
๐ง Using Django ORM to Interact with Databases
The Django ORM lets you work with databases using Python objects, rather than writing raw SQL. It handles everything from table creation to complex queries in a clean, high-level API.
๐ง 1. Defining Models (Tables)
In Django, each model class represents a table in your database.
Example:
python
Copy
Edit
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
is_available = models.BooleanField(default=True)
def __str__(self):
return self.title
models.CharField → maps to VARCHAR
models.DateField → maps to DATE
models.BooleanField → maps to BOOLEAN
⚙️ 2. Creating the Table
After defining your model, run these commands to create the actual database tables:
bash
Copy
Edit
python manage.py makemigrations
python manage.py migrate
✍️ 3. CRUD Operations Using Django ORM
✅ Create
python
Copy
Edit
book = Book.objects.create(
title="1984",
author="George Orwell",
published_date="1949-06-08"
)
๐ Read
Get all books:
python
Copy
Edit
books = Book.objects.all()
Filter by author:
python
Copy
Edit
orwell_books = Book.objects.filter(author="George Orwell")
Get a single book:
python
Copy
Edit
book = Book.objects.get(id=1) # Raises error if not found
Get or return None:
python
Copy
Edit
book = Book.objects.filter(id=1).first()
๐ Update
python
Copy
Edit
book = Book.objects.get(id=1)
book.is_available = False
book.save()
❌ Delete
python
Copy
Edit
book = Book.objects.get(id=1)
book.delete()
๐ 4. Advanced Queries
Ordering:
python
Copy
Edit
Book.objects.order_by('published_date') # Ascending
Book.objects.order_by('-published_date') # Descending
Chaining filters:
python
Copy
Edit
Book.objects.filter(author="George Orwell", is_available=True)
Field lookups:
python
Copy
Edit
Book.objects.filter(title__icontains="war") # Case-insensitive search
Book.objects.filter(published_date__year=1949)
๐ฆ 5. Using Django Admin (Optional Bonus)
Register your model in admin.py to manage it via Django's built-in admin interface:
python
Copy
Edit
from django.contrib import admin
from .models import Book
admin.site.register(Book)
✅ Summary
Task ORM Command Example
Create Book.objects.create(...)
Read Book.objects.all(), get(), filter()
Update book.save() after modifying a field
Delete book.delete()
Learn Full Stack Python Course in Hyderabad
Read More
How to Connect Python with SQL Databases
Setting Up PostgreSQL for Full Stack Python Projects
SQL vs NoSQL: What’s Best for Full Stack Python Development?
Introduction to Databases for Full Stack Python Development
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment