I'll help you create decorators that can dynamically control select_related and prefetch_related for specific ViewSet actions. Here's a solution that allows you to optimize queries on a per-endpoint basis:
from functools import wraps
from django.db.models import Prefetch
def with_select_related(*fields):
"""
Decorator to dynamically add select_related fields to a ViewSet action.
Usage:
@with_select_related('author', 'category')
@action(detail=False, methods=['get'])
def custom_action(self, request):
...
"""
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Store the select_related fields on the view instance
if not hasattr(self, '_select_related_fields'):
self._select_related_fields = []
self._select_related_fields.extend(fields)
# Call the original function
result = func(self, *args, **kwargs)
# Clean up after the request
if hasattr(self, '_select_related_fields'):
self._select_related_fields = []
return result
# Also store fields as an attribute on the function itself
# This is useful for ViewSet methods like list, retrieve, etc.
wrapper._select_related_fields = fields
return wrapper
return decorator
def with_prefetch_related(*fields):
"""
Decorator to dynamically add prefetch_related fields to a ViewSet action.
Usage:
@with_prefetch_related('comments', 'tags')
@action(detail=False, methods=['get'])
def custom_action(self, request):
...
For complex prefetches, you can pass Prefetch objects:
@with_prefetch_related(
Prefetch('comments', queryset=Comment.objects.select_related('author'))
)
"""
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Store the prefetch_related fields on the view instance
if not hasattr(self, '_prefetch_related_fields'):
self._prefetch_related_fields = []
self._prefetch_related_fields.extend(fields)
# Call the original function
result = func(self, *args, **kwargs)
# Clean up after the request
if hasattr(self, '_prefetch_related_fields'):
self._prefetch_related_fields = []
return result
# Also store fields as an attribute on the function itself
wrapper._prefetch_related_fields = fields
return wrapper
return decorator
class OptimizedQuerySetMixin:
"""
Mixin for ViewSets that enables dynamic query optimization through decorators.
"""
def get_queryset(self):
"""
Override get_queryset to apply dynamic select_related and prefetch_related.
"""
queryset = super().get_queryset()
# Get the current action being called
action = self.action
action_func = getattr(self, action, None)
select_related_fields = []
prefetch_related_fields = []
# Check if the action function has optimization attributes
if action_func:
if hasattr(action_func, '_select_related_fields'):
select_related_fields.extend(action_func._select_related_fields)
if hasattr(action_func, '_prefetch_related_fields'):
prefetch_related_fields.extend(action_func._prefetch_related_fields)
# Also check instance attributes (for custom actions)
if hasattr(self, '_select_related_fields'):
select_related_fields.extend(self._select_related_fields)
if hasattr(self, '_prefetch_related_fields'):
prefetch_related_fields.extend(self._prefetch_related_fields)
# Apply select_related if fields are specified
if select_related_fields:
queryset = queryset.select_related(*select_related_fields)
# Apply prefetch_related if fields are specified
if prefetch_related_fields:
queryset = queryset.prefetch_related(*prefetch_related_fields)
return queryset
Here's how to use these decorators in your ViewSets:
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Book, Author, Comment
from .serializers import BookSerializer, BookDetailSerializer
class BookViewSet(OptimizedQuerySetMixin, viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
# Optimize the list endpoint
@with_select_related('author', 'publisher')
@with_prefetch_related('tags')
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
# Optimize the retrieve endpoint with more relations
@with_select_related('author', 'publisher', 'category')
@with_prefetch_related('comments', 'tags', 'reviews')
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)
# Custom action with specific optimizations
@with_select_related('author')
@with_prefetch_related(
Prefetch('comments', queryset=Comment.objects.select_related('user'))
)
@action(detail=False, methods=['get'])
def recent_with_comments(self, request):
queryset = self.filter_queryset(self.get_queryset())
queryset = queryset.filter(created_at__gte=timezone.now() - timedelta(days=7))
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
# Another custom action with different optimizations
@with_prefetch_related('tags', 'reviews')
@action(detail=False, methods=['get'])
def popular(self, request):
queryset = self.filter_queryset(self.get_queryset())
queryset = queryset.filter(rating__gte=4.0)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
You can also combine both decorators and use them with complex Prefetch objects:
from django.db.models import Prefetch, Count
class AuthorViewSet(OptimizedQuerySetMixin, viewsets.ModelViewSet):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
@with_select_related('profile', 'country')
@with_prefetch_related(
Prefetch(
'books',
queryset=Book.objects.select_related('publisher').annotate(
comment_count=Count('comments')
)
),
'awards'
)
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)
This solution provides several benefits:
- Per-endpoint optimization: You can specify exactly which relations to load for each endpoint
- Clean syntax: Decorators make it clear which optimizations apply to which endpoints
- Flexibility: Supports both simple field names and complex Prefetch objects
- No global overhead: Only the decorated endpoints will have the optimizations applied
- Reusability: The mixin can be used across multiple ViewSets
The decorators work by temporarily storing the field information either as function attributes or instance attributes, which are then picked up by the get_queryset method in the mixin. This ensures that each endpoint only loads the data it actually needs.