Here's an implementation of the two decorators you requested. These decorators will allow you to dynamically specify the fields for select_related and prefetch_related on a per-action basis in your ViewSets.
# decorators.py
from functools import wraps
from rest_framework import viewsets
def with_select_related(fields):
"""
Decorator to dynamically set select_related fields on a ViewSet action.
Args:
fields (list): List of field names to apply select_related on.
Example:
@with_select_related(['author', 'category'])
def list(self, request):
...
"""
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Check if get_queryset is overridden
if not hasattr(self, '_base_get_queryset'):
self._base_get_queryset = self.get_queryset
def new_get_queryset(self):
qs = self._base_get_queryset()
return qs.select_related(*fields)
self.get_queryset = new_get_queryset.__get__(self)
else:
# If get_queryset is already overridden by another decorator,
# we need to chain the select_related calls
orig_get_queryset = self.get_queryset
def new_get_queryset(self):
qs = orig_get_queryset()
return qs.select_related(*fields)
self.get_queryset = new_get_queryset.__get__(self)
return func(self, *args, **kwargs)
return wrapper
return decorator
def with_prefetch_related(fields):
"""
Decorator to dynamically set prefetch_related fields on a ViewSet action.
Args:
fields (list): List of field names to apply prefetch_related on.
Example:
@with_prefetch_related(['tags', 'comments'])
def retrieve(self, request, pk=None):
...
"""
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Check if get_queryset is overridden
if not hasattr(self, '_base_get_queryset'):
self._base_get_queryset = self.get_queryset
def new_get_queryset(self):
qs = self._base_get_queryset()
return qs.prefetch_related(*fields)
self.get_queryset = new_get_queryset.__get__(self)
else:
# If get_queryset is already overridden by another decorator,
# we need to chain the prefetch_related calls
orig_get_queryset = self.get_queryset
def new_get_queryset(self):
qs = orig_get_queryset()
return qs.prefetch_related(*fields)
self.get_queryset = new_get_queryset.__get__(self)
return func(self, *args, **kwargs)
return wrapper
return decorator
How it works:
- Each decorator (
with_select_related and with_prefetch_related) takes a list of field names as an argument.
- When you apply the decorator to a ViewSet action (e.g.,
list, retrieve, etc.), it wraps the original action function.
- Inside the wrapper, it checks if the
get_queryset method has already been overridden (e.g., by another decorator). If not, it saves the original get_queryset method as _base_get_queryset and creates a new get_queryset method that applies the select_related or prefetch_related call with the specified fields.
- If
get_queryset is already overridden, it chains the select_related or prefetch_related calls by creating a new get_queryset method that calls the original one and then applies the additional optimization.
- The wrapper then calls the original action function (
func) with the modified get_queryset method.
Example usage:
# viewsets.py
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
from .decorators import with_select_related, with_prefetch_related
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
def get_queryset(self):
# Your base queryset with some initial optimizations
qs = super().get_queryset()
qs = qs.select_related('author') # Always select author
return qs
@with_select_related(['publisher']) # Add publisher to select_related
def list(self, request):
return super().list(request)
@with_prefetch_related(['tags', 'comments']) # Prefetch tags and comments
def retrieve(self, request, pk=None):
return super().retrieve(request, pk=pk)
@with_select_related(['category']) # Select category, chaining with author
@with_prefetch_related(['reviews']) # Prefetch reviews
def get_featured_books(self, request):
# Custom action
qs = self.get_queryset().filter(is_featured=True)
serializer = self.get_serializer(qs, many=True)
return Response(serializer.data)
In this example:
- The
get_queryset method always selects the author relation.
- The
list action additionally selects the publisher relation.
- The
retrieve action prefetches tags and comments.
- The custom
get_featured_books action selects the category relation (chaining with author) and prefetches reviews.
By using these decorators, you can easily customize the queryset optimizations on a per-action basis without duplicating code or overriding get_queryset multiple times.
Note: Be mindful of the order of decorators when stacking them (as shown in get_featured_books). The order determines the order of select_related and prefetch_related calls, which might impact performance. Generally, select_related should come before prefetch_related for optimal results.