python / intermediate
Snippet
Custom QuerySet Methods for Domain Logic Encapsulation
Subclassing Django's models.QuerySet allows chaining reusable, domain-specific database queries directly on your model manager using as_manager().
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from django.db import modelsclass ArticleQuerySet(models.QuerySet):def published(self):return self.filter(status='published')def written_by(self, author):return self.filter(author=author)class Article(models.Model):title = models.CharField(max_length=200)status = models.CharField(max_length=20)author = models.CharField(max_length=100)objects = ArticleQuerySet.as_manager()
django
Breakdown
1
class ArticleQuerySet(models.QuerySet):
Defines a custom QuerySet class inheriting from Django's base QuerySet.
2
def published(self):
Encapsulates a specific filter operation into a reusable QuerySet method.
3
objects = ArticleQuerySet.as_manager()
Exposes the custom QuerySet methods directly through the model's default manager.