1. What is Django REST Framework (DRF), and why use it over plain Django views?
Answer:
Django REST Framework is a toolkit built on top of Django designed to make building Web APIs fast, consistent, and maintainable. While plain Django views can return JsonResponse, DRF provides built-in solutions for:
- Serialization & Deserialization: Converting model instances/QuerySets to JSON (and validating incoming payloads).
- Authentication & Permissions: Pluggable auth schemes (Session, Token, JWT via third-party packages) and view/object-level permission classes.
- Generic Views, ViewSets & Routers: Reducing boilerplate for standard CRUD operations.
- Browsable API: An interactive web interface useful during development and testing.
- Pagination, Throttling, Filtering & Versioning: Production API essentials out of the box.
![]()
2. What is the difference between Serializer and ModelSerializer?
Answer:
serializers.Serializer: Gives you full explicit control over fields, validation, and how.create()and.update()behave. Best when data doesn't map directly to a single Django model (e.g., aggregating data, custom payloads, or non-ORM sources).serializers.ModelSerializer: Automatically generates serializer fields from a Django model and provides default.create()and.update()implementations. You can still customize fields (fields,exclude,read_only_fields,extra_kwargs) and add customvalidate_<field>()orvalidate()methods.
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ["id", "title", "slug", "created_at"]
read_only_fields = ["id", "slug", "created_at"]
3. How does validation work in DRF serializers?
Answer:
DRF runs validation in a clear sequence when .is_valid() is called:
- Field-level validation: Built-in field constraints (e.g.,
max_length,required,allow_blank) and customvalidate_<field_name>(self, value)methods. - Object-level validation: Cross-field checks inside
validate(self, attrs)(e.g., ensuringend_dateis afterstart_date). - Validators: Functions or callable classes passed via the
validators=[...]argument on a field orMeta.
Any validation error should raise serializers.ValidationError(...), which DRF turns into a 400 Bad Request response with structured error details.
4. What is the difference between APIView, GenericAPIView, and ViewSet (ModelViewSet)?
Answer:
APIView: Wraps Django'sViewand gives you direct handler methods (get,post,put,patch,delete) with DRF'sRequest/Responseobjects, auth, permissions, and exception handling. Best for custom endpoints that don't revolve around standard CRUD.GenericAPIView: ExtendsAPIViewwithqueryset,serializer_class,lookup_field, pagination, and filtering helpers. Commonly paired with mixins or generic concrete views (ListCreateAPIView,RetrieveUpdateDestroyAPIView).ViewSet/ModelViewSet: Groups related actions (list,create,retrieve,update,partial_update,destroy) into a single class instead of mapping HTTP methods directly. When registered with a DRFRouter(DefaultRouterorSimpleRouter), URLs are generated automatically.
5. How do you prevent N+1 query issues in DRF?
Answer:
N+1 queries often happen in serializers when accessing foreign keys or reverse/many-to-many relations across a list of objects. You fix this at the QuerySet level before serialization:
select_related(): Uses SQLJOINs for single-valued relationships (ForeignKeyandOneToOneField).prefetch_related(): Runs separate queries and joins results in Python for reverseForeignKeyandManyToManyFieldrelationships.
class CommentViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = CommentSerializer
def get_queryset(self):
return (
Comment.objects.select_related("author", "post")
.prefetch_related("tags")
.order_by("-created_at")
)
6. What is the difference between Authentication and Authorization (Permissions) in DRF?
Answer:
- Authentication answers "Who are you?" It runs at the start of the request to identify the user and populate
request.userandrequest.auth(e.g.,SessionAuthentication,TokenAuthentication, or JWT). If authentication fails, DRF typically returns401 Unauthorizedor403 Forbiddendepending on the authenticator. - Authorization (Permissions) answers "Are you allowed to do this?" After authentication, DRF checks
permission_classes(such asIsAuthenticated,IsAdminUser,DjangoModelPermissions, or custom permission classes). View permissions check the request/view, while object permissions (has_object_permission) run when retrieving or modifying a specific object.
7. How do you implement custom object-level permissions in DRF?
Answer:
Subclass rest_framework.permissions.BasePermission and implement has_object_permission(self, request, view, obj) (and has_permission if needed). Note that DRF does not automatically call has_object_permission on list views—it triggers on detail actions or when you explicitly call self.check_object_permissions(request, obj).
from rest_framework import permissions
class IsAuthorOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.author == request.user
8. What is the difference between PUT and PATCH in REST and DRF?
Answer:
PUTrepresents a full replacement of the resource. All required writable fields are expected; omitting required fields typically triggers validation errors.PATCHrepresents a partial update of the resource. Only the fields provided in the request payload are updated. In DRF serializers, passingpartial=True(whichUpdateModelMixin.partial_updatedoes automatically forPATCH) skipsrequiredchecks on omitted fields while still validating provided values.
9. How does pagination work in DRF, and which pagination class should you choose?
Answer:
Pagination splits large result sets into manageable chunks so clients don't download massive payloads at once. Common DRF pagination classes include:
PageNumberPagination: Uses?page=2&page_size=20. Great for standard page-based UIs, though deep offsets (OFFSET) can get slower on very large tables.LimitOffsetPagination: Uses?limit=20&offset=40, giving clients flexible slicing similar to SQLLIMIT/OFFSET.CursorPagination: Uses an opaque cursor based on a unique, ordered field (likecreated_atorid). Best for large datasets and real-time feeds because it avoids offset drift when new items are inserted and performs consistently.
10. How do throttling and API versioning work in DRF?
Answer:
- Throttling controls request rates to protect your API from abuse, scraping, or accidental traffic spikes. You configure
DEFAULT_THROTTLE_CLASSES(such asAnonRateThrottleandUserRateThrottle) andDEFAULT_THROTTLE_RATES(e.g.,"100/hour","1000/day"). When exceeded, DRF returns429 Too Many Requestswith aRetry-Afterheader. - Versioning lets you evolve breaking API changes without breaking existing clients. DRF supports schemes like
URLPathVersioning(/api/v1/items/),NamespaceVersioning,HostNameVersioning,QueryParameterVersioning(?version=1.0), andAcceptHeaderVersioning. The active version is available onrequest.version, and the scheme onrequest.versioning_scheme.