python / intermediate
Snippet
Custom Model Manager Method Returning Flattened List Collections
Custom QuerySets encapsulate data retrieval patterns into reusable methods. Using `.values_list('sku', flat=True)` flattens single-column database queries directly into standard Python lists.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.db import modelsclass ProductQuerySet(models.QuerySet):def extract_active_sku_list(self) -> list[str]:return list(self.filter(is_active=True).values_list("sku", flat=True).distinct())class Product(models.Model):sku = models.CharField(max_length=30, unique=True)is_active = models.BooleanField(default=True)objects = ProductQuerySet.as_manager()
django
Breakdown
1
class ProductQuerySet(models.QuerySet):
Defines a custom QuerySet subclass to encapsulate reusable domain queries.
2
def extract_active_sku_list(self) -> list[str]:
Defines a manager method returning a typed list of SKU strings.
3
.values_list("sku", flat=True)
Retrieves values as single flat tuples/list items instead of tuple objects.
4
objects = ProductQuerySet.as_manager()
Attaches the custom QuerySet methods directly to the Django Model manager.