🎸 Django Intermediate

What is Django custom manager and QuerySet?

Why Interviewers Ask This

This question targets practical, hands-on experience with Django. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

Custom managers and QuerySets encapsulate reusable query logic in the model layer: Custom QuerySet: class ArticleQuerySet(models.QuerySet): def published(self): return self.filter(is_published=True) def by_author(self, user): return self.filter(author=user) def with_stats(self): return self.annotate(comment_count=Count("comments"), like_count=Count("likes")) def recent(self): return self.order_by("-published_at")[:10]. Custom Manager: class ArticleManager(models.Manager): def get_queryset(self): return ArticleQuerySet(self.model, using=self._db) def published(self): return self.get_queryset().published() def for_homepage(self): return self.published().with_stats().recent(). Apply to model: class Article(models.Model): ... objects = ArticleManager() # Replace default manager. Chaining (from_queryset): ArticleManager = models.Manager.from_queryset(ArticleQuerySet) class Article(models.Model): objects = ArticleManager(). Usage: Article.objects.published() Article.objects.published().by_author(user).with_stats() Article.objects.for_homepage(). Multiple managers: class Article(models.Model): objects = models.Manager() # Default all articles published = ArticleManager() # Published only. Use: Article.published.all(). First manager is default — affects admin and related lookups.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Django answers easy to follow.