Introduction
Django ORM (Object-Relational Mapping) is a powerful feature that allows developers to interact with databases using Python code instead of SQL. It abstracts the underlying database layer and enables developers to perform CRUD operations (Create, Read, Update, Delete) seamlessly. This guide provides a comprehensive overview of Django ORM, starting with model creation and ending with advanced querying techniques.
What is Django ORM?
ORM is a way to map data models in your code to the underlying database structure. In Django, ORM makes it possible to work with data without writing raw SQL queries. Each table in the database is represented by a model class in Django, and ORM translates Python code into SQL behind the scenes.
Setting Up a Django Project
- Create a Project:
django-admin startproject orm_project cd orm_project - Create an App:
python manage.py startapp myapp - Add App to Installed Apps:
Opensettings.pyand add'myapp'to theINSTALLED_APPSlist:INSTALLED_APPS = [ ... 'myapp', ] - Run Migrations:
Ensure the default database is set up correctly:python manage.py migrate
Defining Django Models
Models are Python classes that define the structure of your database tables. Let’s create a model for a simple blog application:
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
Creating and Applying Migrations
After defining your models, run the following commands to create and apply migrations:
python manage.py makemigrations
python manage.py migrate
Performing CRUD Operations with Django ORM
1. Creating Records
Creating records in Django ORM is straightforward:
from myapp.models import BlogPost
post = BlogPost(
title="Django ORM Basics",
content="This is an introductory post on Django ORM.",
author="John Doe"
)
post.save()
Alternatively, you can use the create() method:
BlogPost.objects.create(
title="Another Post",
content="This is another blog post.",
author="Jane Doe"
)
2. Reading Records
To retrieve records from the database, use Django’s query methods:
# Get all posts
posts = BlogPost.objects.all()
# Get a single post by primary key (ID)
post = BlogPost.objects.get(id=1)
# Filter posts by a specific condition
filtered_posts = BlogPost.objects.filter(author="John Doe")
For more complex queries:
posts = BlogPost.objects.filter(author="John Doe").order_by('-created_at')
3. Updating Records
To update a record:
post = BlogPost.objects.get(id=1)
post.title = "Updated Title"
post.save()
To update multiple records:
BlogPost.objects.filter(author="John Doe").update(author="Jonathan Doe")
4. Deleting Records
To delete a record:
post = BlogPost.objects.get(id=1)
post.delete()
To delete multiple records:
BlogPost.objects.filter(author="Jonathan Doe").delete()
Advanced Querying with Django ORM
1. QuerySet Methods
all(): Retrieves all records.filter(): Filters records based on conditions.exclude(): Excludes records that match specific conditions.order_by(): Orders records by one or more fields.distinct(): Returns distinct records.
2. Aggregations
Django ORM supports aggregation functions like Count and Avg:
from django.db.models import Count, Avg
# Count the number of posts by each author
author_count = BlogPost.objects.values('author').annotate(count=Count('author'))
# Calculate the average length of content
average_length = BlogPost.objects.aggregate(Avg('content__length'))
Using Django Admin to Manage Data
Register your model with the admin site by modifying admin.py:
from django.contrib import admin
from .models import BlogPost
admin.site.register(BlogPost)
Create a superuser to access the admin panel:
python manage.py createsuperuser
Log in to the admin site at http://127.0.0.1:8000/admin/.
Optimizing Queries with Select Related and Prefetch Related
Use select_related() and prefetch_related() to optimize queries:
# Using select_related
posts = BlogPost.objects.select_related('author').all()
# Using prefetch_related
posts = BlogPost.objects.prefetch_related('tags').all()
0 Comments