In Django, custom queries and model managers provide a powerful way to encapsulate reusable query logic. Model managers allow you to define custom methods that simplify complex queries, making them reusable across your application. This improves readability, maintainability, and performance of database operations.
A model manager is a custom class that extends models.Manager. By default, Django provides objects as the manager, but custom managers allow you to define domain-specific query methods.
# Custom manager to encapsulate reusable queries
from django.db import models
class ProductManager(models.Manager):
def in_stock(self):
return self.filter(stock__gt=0)
def expensive_products(self):
return self.filter(price__gt=100)
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField()
objects = ProductManager()
# Using custom manager methods
in_stock_products = Product.objects.in_stock()
expensive_products = Product.objects.expensive_products()
# Fetch products using custom manager methods
in_stock_products = Product.objects.in_stock()
expensive_products = Product.objects.expensive_products()
# Chain multiple custom manager methods
in_stock_expensive_products = Product.objects.in_stock().expensive_products()
# Custom QuerySet for advanced chaining
from django.db import models
class ProductQuerySet(models.QuerySet):
def in_stock(self):
return self.filter(stock__gt=0)
def expensive(self):
return self.filter(price__gt=100)
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField()
objects = ProductQuerySet.as_manager()
# QuerySet-based queries
in_stock_products = Product.objects.in_stock()
expensive_products = Product.objects.expensive()
Click the buttons to simulate how Django Managers filter the database.