Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Note: Before submitting a code change, please review our contributing guidelines.
Description
This PR adds automatic query optimization capabilities to Django REST Framework, helping developers prevent N+1 query problems by automatically analyzing serializer fields and applying
select_related()andprefetch_related()optimizations.Problem Statement
N+1 query problems are one of the most common performance issues in Django REST Framework applications. Developers often forget to optimize querysets when using serializers with related fields, leading to:
Currently, DRF requires developers to manually optimize querysets in
get_queryset()methods, which is error-prone and easy to forget.Solution
This feature provides:
select_related()andprefetch_related()automaticallyImplementation Details
New Module:
rest_framework.optimizationCore Components:
query_analyzer.py:QueryAnalyzerclass: Analyzes serializer fields to detect relationshipsdetect_n_plus_one(): Detects potential N+1 queries in querysetsoptimizer.py:optimize_queryset(): Applies query optimizations to querysetsanalyze_serializer_fields(): Analyzes serializer for optimization needsget_optimization_suggestions(): Provides code examples for optimizationmixins.py:OptimizedQuerySetMixin: Mixin for automatic query optimization in viewsetsmiddleware.py:QueryOptimizationMiddleware: Optional middleware for development-time N+1 detectionSettings
Added two new settings to
REST_FRAMEWORK:ENABLE_QUERY_OPTIMIZATION: Enable/disable automatic optimization (default:True)WARN_ON_N_PLUS_ONE: Show warnings when N+1 queries detected (default:None, auto-detects based onDEBUG)Tests
tests/test_optimization.pyUsage Examples
Basic Usage
Manual Optimization
Explicit Fields
Features
✅ Automatic Field Detection
select_related()prefetch_related()PrimaryKeyRelatedField(many=True))✅ Smart Optimization
✅ Development Warnings
Code Quality
✅ Follows DRF Standards
model_meta.get_field_info)✅ Testing
Backward Compatibility
Performance Impact
Files Changed
New Files:
rest_framework/optimization/__init__.pyrest_framework/optimization/query_analyzer.pyrest_framework/optimization/optimizer.pyrest_framework/optimization/mixins.pyrest_framework/optimization/middleware.pytests/test_optimization.pyModified Files:
rest_framework/settings.py(added optimization settings)Breaking Changes
None. This is a purely additive feature.
Migration Guide
No migration needed. The feature works out of the box:
Checklist
Notes
This feature addresses one of the top 3 most common issues developers face with DRF (N+1 query problems). While DRF is considered feature-complete, this enhancement significantly improves developer experience and application performance without breaking existing functionality.