python / intermediate
Snippet
Django Custom Model Manager with Chaining Methods
Custom managers allow you to define reusable query logic directly on your models. By chaining custom methods with Django's QuerySet methods, you create a fluent API for common queries. The default.objects manager remains accessible while adding a custom published manager for publication-specific queries.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from django.db import modelsfrom django.utils import timezoneclass PublishedManager(models.Manager):def get_queryset(self):return super().get_queryset().filter(status='published')def by_year(self, year):return self.get_queryset().filter(published_at__year=year)def this_month(self):now = timezone.now()return self.get_queryset().filter(published_at__month=now.month,published_at__year=now.year)class Article(models.Model):title = models.CharField(max_length=200)status = models.CharField(max_length=10, default='draft')published_at = models.DateTimeField(null=True, blank=True)objects = models.Manager()published = PublishedManager()class Meta:ordering = ['-published_at']# Usage examples:Article.published.all() # Only published articlesArticle.published.by_year(2024) # Published in 2024Article.published.this_month() # Published this monthArticle.published.by_year(2024).count()
django
Breakdown
1
class PublishedManager(models.Manager):
Extend models.Manager to create custom manager with publication-specific logic
2
def get_queryset(self):
Override to return filtered queryset by default - only 'published' status articles
3
def by_year(self, year):
Custom method that returns QuerySet filtered by publication year, chainable
4
def this_month(self):
Uses timezone.now() to filter articles published in current month
5
objects = models.Manager()
Keep default Manager accessible alongside custom manager
6
published = PublishedManager()
Custom manager instance allows Article.published.* query interface
7
Article.published.by_year(2024).count()
Chain custom methods with QuerySet methods for powerful, readable queries