Python | Algorithms | Data Structures | Cyber ​​Security | Networks
38.6K subscribers
778 photos
23 videos
21 files
713 links
This channel is for Programmers, Coders, Software Engineers.

1) Python
2) django
3) python frameworks
4) Data Structures
5) Algorithms
6) DSA

Admin: @Hussein_Sheikho

Ad & Earn money form your channel:
https://telega.io/?r=nikapsOH
Download Telegram
Topic: Django ORM – Transactions, Subqueries, and Custom Managers (Part 3)

---

1. Working with Transactions

• Django supports atomic transactions to ensure database integrity — either all operations succeed, or none do.

from django.db import transaction

@transaction.atomic
def create_author_and_book():
author = Author.objects.create(name="New Author")
Book.objects.create(title="New Book", author=author)


• Use atomic() as a decorator or context manager.

with transaction.atomic():
# multiple operations that must succeed together
...


---

2. Subqueries and OuterRef

• Use Subquery and OuterRef to perform queries that depend on other queries.

from django.db.models import Subquery, OuterRef

# Get latest book for each author
latest_books = Book.objects.filter(author=OuterRef('pk')).order_by('-published_date')
authors = Author.objects.annotate(latest_book=Subquery(latest_books.values('title')[:1]))


---

3. Exists() and Conditional Logic

• Use Exists for optimized existence checks.

from django.db.models import Exists

recent_books = Book.objects.filter(published_date__year=2023)
authors = Author.objects.annotate(has_recent_books=Exists(recent_books.filter(author=OuterRef('pk'))))


---

4. Custom Model Managers

• Add custom query logic to models via custom managers.

from django.db import models

class PublishedBookManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_published=True)

class Book(models.Model):
title = models.CharField(max_length=200)
is_published = models.BooleanField(default=False)

objects = models.Manager() # Default manager
published = PublishedBookManager() # Custom manager


# Usage
Book.published.all()


---

5. QuerySet Methods: Update, Delete, Bulk Operations

update() modifies multiple records efficiently.

Book.objects.filter(author__name="Alice").update(pages=300)


delete() removes objects in bulk.

Book.objects.filter(published_date__year__lt=2000).delete()


bulk\_create() inserts many records at once.

Book.objects.bulk_create([
Book(title="Book A", author=author),
Book(title="Book B", author=author),
])


---

6. Using Database Functions

• Django provides built-in SQL functions like Lower, Upper, Length, Concat, etc.

from django.db.models.functions import Upper

books = Book.objects.annotate(upper_title=Upper('title'))


---

Summary

• Use transactions to maintain data integrity.

• Leverage subqueries, OuterRef, and Exists for complex logic.

• Create custom managers to encapsulate reusable query logic.

• Apply bulk operations and DB functions for performance and flexibility.

---

Exercise

• Create a custom manager for the Book model to return only books published in the last 5 years. Then use this manager in a view to list all recent books along with their authors.

---

#Django #ORM #Transactions #Subqueries #CustomManagers #AdvancedDjango

https://t.iss.one/DataScience4
5