Django ORM

Querying the database using Django ORM:

Django ORM allows you to interact with your database using Python code, without needing to write SQL queries directly.

You can perform CRUD (Create, Read, Update, Delete) operations and more.

                                
from myapp.models import Post

# Retrieve all posts
all_posts = Post.objects.all()

# Retrieve a single post by filtering
post = Post.objects.get(id=1)

# Create a new post
new_post = Post(title="New Post", content="This is a new post.")
new_post.save()

# Update an existing post
post.title = "Updated Title"
post.save()

# Delete a post
post.delete()

                                
                            

Filtering, ordering, and aggregating data:

Django ORM provides methods for filtering, ordering, and aggregating data.

                                
# Filtering data
filtered_posts = Post.objects.filter(category='Technology')

# Ordering data
ordered_posts = Post.objects.order_by('-created_at')  # descending order

# Aggregating data
from django.db.models import Count
post_count = Post.objects.aggregate(total=Count('id'))

                                
                            

Advanced ORM features:

Django ORM offers advanced features like raw SQL queries and annotations.

  • Raw SQL queries: You can execute raw SQL queries using the raw() method.
                                
from django.db import connection

raw_query = "SELECT * FROM myapp_post WHERE category = %s"
posts = Post.objects.raw(raw_query, ['Technology'])

# Access raw results
for post in posts:
    print(post.title)

                                
                            

  • Annotations: allow you to perform calculations on querysets.
                                
from django.db.models import Count

# Annotate queryset with count of comments for each post
annotated_posts = Post.objects.annotate(comment_count=Count('comments'))

# Access annotated results
for post in annotated_posts:
    print(post.title, post.comment_count)