MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Signals & Model Managers0%
Study Materials
Django for Backend DevelopmentProgress 0%
1.1Installing Django & Environment Setup1.2Django Project Structure1.3Creating First Django App
8.1Signals & Model Managers8.2Query Optimization8.3Django Template Filters & Tags
HomeTutorialsDjango for Backend DevelopmentSignals & Model Managers
Query Optimization

Signals & Model Managers

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

As enterprise applications grow, cleanly decoupling domain actions and encapsulating repetitive database queries is essential. Django Signals implement a publish-subscribe pattern that allows decoupled applications to receive notifications when specific events occur. Custom Model Managers extend the ORM, allowing you to define domain-specific query methods that keep view logic clean.


1. Custom Model Managers and QuerySets

Encapsulate common filtering logic directly on your models:

1# articles/models.py
2from django.db import models
3 
4# 1. Custom QuerySet defining chainable domain queries
5class ArticleQuerySet(models.QuerySet):
6 def published(self):
7 return self.filter(status="published")
8 
9 def featured(self):
10 return self.filter(is_featured=True)
11 
12 def by_author(self, user):
13 return self.filter(author=user)
14 
15 def popular(self, min_views=1000):
16 return self.filter(view_count__gte=min_views)
17 
18# 2. Model Manager using the custom QuerySet
19class ArticleManager(models.Manager):
20 def get_queryset(self):
21 return ArticleQuerySet(self.model, using=self._db)
22 
23 # Proxy methods to enable chainable calls: Article.objects.published().featured()
24 def published(self):
25 return self.get_queryset().published()
26 
27 def featured(self):
28 return self.get_queryset().featured()

Attach the manager to the model:

1class Article(models.Model):
2 title = models.CharField(max_length=200)
3 status = models.CharField(max_length=20, default="draft")
4 is_featured = models.BooleanField(default=False)
5 view_count = models.PositiveIntegerField(default=0)
6 
7 # Attach custom manager
8 objects = ArticleManager()
9 
10 # Optional: Dedicated manager for published articles
11 published_objects = ArticleManager()

Clean, Readable View Code:

1# Expressive, DRY, chainable queries!
2hero_articles = Article.objects.published().featured().popular()

2. Django Signals: Publish / Subscribe Pattern

Signals allow decoupled senders to notify subscribed receivers when events happen:

  • post_save: Sent immediately after a model instance is saved.
  • post_delete: Sent after an instance is deleted.
  • m2m_changed: Sent when a ManyToMany field is modified.
  • user_logged_in: Sent when a user authenticates.

3. Implementing Automated Profile Creation with post_save

A classic enterprise use case: automatically creating a UserProfile record whenever a new User is created:

1# accounts/signals.py
2from django.db.models.signals import post_save
3from django.dispatch import receiver
4from django.conf import settings
5from .models import UserProfile
6 
7@receiver(post_save, sender=settings.AUTH_USER_MODEL)
8def create_user_profile(sender, instance, created, **kwargs):
9 if created:
10 # Only execute on initial record creation, not updates
11 UserProfile.objects.create(user=instance)
12 print(f"Provisioned UserProfile for new user: {instance.email}")
13 
14@receiver(post_save, sender=settings.AUTH_USER_MODEL)
15def save_user_profile(sender, instance, **kwargs):
16 # Ensure profile is saved if updated
17 if hasattr(instance, "profile"):
18 instance.profile.save()

4. Connecting Signals in apps.py

Signals must be imported inside your application configuration's ready() method:

1# accounts/apps.py
2from django.apps import AppConfig
3 
4class AccountsConfig(AppConfig):
5 default_auto_field = "django.db.models.BigAutoField"
6 name = "accounts"
7 
8 def ready(self):
9 # Register signals when app registry is fully populated
10 import accounts.signals

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary benefit of defining Custom Model Managers in Django?
Question 2
What parameter passed to a post_save signal handler indicates whether the record was newly inserted?
Question 3
Where should signal handlers be connected to guarantee they load reliably on server boot?
Question 4
Why is receiver(post_save, sender=settings.AUTH_USER_MODEL) preferred over hardcoding the sender class?
Question 5
What is a potential hazard of overusing Django Signals for core business logic?
Next Lesson

Query Optimization

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Security Best PracticesQuery Optimization

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Django for Backend Development with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext