Django Django REST Framework 2 — Questions and Answers
Question 1: What does DRF's `APIView` class provide over Django's standard `View`?
- Request parsing, authentication, permission checking, and content negotiation for APIs (Correct answer)
- Automatic database CRUD operations
- Built-in pagination and filtering
- GraphQL schema generation
Correct answer: Request parsing, authentication, permission checking, and content negotiation for APIs
APIView wraps Django's View with DRF's Request/Response objects, authentication, permissions, throttling, and content negotiation.
Question 2: What does `serializer.is_valid(raise_exception=True)` do in DRF?
- Validates the serializer data and automatically returns a 400 response if invalid (Correct answer)
- Raises a Python exception that crashes the server
- Validates and saves the data in one step
- Skips validation and saves directly
Correct answer: Validates the serializer data and automatically returns a 400 response if invalid
With raise_exception=True, DRF automatically returns a 400 Bad Request response with validation errors instead of requiring manual error handling.
Question 3: What is DRF's `Router` used for?
- Automatically generating URL patterns for ViewSet actions (Correct answer)
- Routing requests to different database shards
- Load balancing API requests
- Defining API versioning schemes
Correct answer: Automatically generating URL patterns for ViewSet actions
Registering a ViewSet with a Router auto-creates standard REST URL patterns for list, detail, create, update, and delete actions.
Question 4: Which DRF permission class allows unrestricted access to an endpoint?
- AllowAny (Correct answer)
- IsPublic
- NoAuth
- OpenAccess
Correct answer: AllowAny
AllowAny grants access to any request, authenticated or not, and is useful for public endpoints like registration or password reset.
Question 5: What does DRF's `@action` decorator do on a ViewSet method?
- Creates a custom endpoint on the ViewSet beyond the standard CRUD actions (Correct answer)
- Marks a method as asynchronous
- Adds authentication to a single ViewSet method
- Caches the result of the ViewSet method
Correct answer: Creates a custom endpoint on the ViewSet beyond the standard CRUD actions
The @action decorator defines additional routes on a ViewSet, specifying detail=True for object-level actions or False for collection-level actions.
Question 6: What is DRF's `throttle_classes` used for?
- Rate-limiting API requests per user or IP to prevent abuse (Correct answer)
- Prioritizing API requests by user role
- Compressing API responses
- Batching multiple API calls
Correct answer: Rate-limiting API requests per user or IP to prevent abuse
throttle_classes applies rate limiting to an API view, with built-in classes like UserRateThrottle and AnonRateThrottle configurable via DEFAULT_THROTTLE_RATES.
What does DRF's `APIView` class provide over Django's standard `View`?