Model Managers
Extend the base Manager class of a model to add/or to modify the initial QuerySet the Manager returns.
There are two main advantages of this:
- Clarity: The implementation detail of the filter can be abstracted away, making logic easier to read.
- Consistency: The same filter can be reused reducing the risk of differing implementations in the codebase.
managers.py
from django.db import models
from django.db.models.functions import Coalesce
class PollManager(models.Manager):
def with_counts(self):
return self.annotate(
num_responses=Coalesce(models.Count("response"), 0)
)
models.py
from django.db import models
from polls.managers import PollManager
class OpinionPoll(models.Model):
question = models.CharField(max_length=200)
objects = PollManager()
class Response(models.Model):
poll = models.ForeignKey(OpinionPoll, on_delete=models.CASCADE)
usage.py
OpinionPoll.objects.with_counts()