Interview Questions

10 Common Django REST Framework Interview Questions & Answers

Author: Interview Questions Posted 8 days ago 40 min read

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 custom validate_<field>() or validate() 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:

  1. Field-level validation: Built-in field constraints (e.g., max_length, required, allow_blank) and custom validate_<field_name>(self, value) methods.
  2. Object-level validation: Cross-field checks inside validate(self, attrs) (e.g., ensuring end_date is after start_date).
  3. Validators: Functions or callable classes passed via the validators=[...] argument on a field or Meta.

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's View and gives you direct handler methods (get, post, put, patch, delete) with DRF's Request/Response objects, auth, permissions, and exception handling. Best for custom endpoints that don't revolve around standard CRUD.
  • GenericAPIView: Extends APIView with queryset, 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 DRF Router (DefaultRouter or SimpleRouter), 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 SQL JOINs for single-valued relationships (ForeignKey and OneToOneField).
  • prefetch_related(): Runs separate queries and joins results in Python for reverse ForeignKey and ManyToManyField relationships.
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.user and request.auth (e.g., SessionAuthentication, TokenAuthentication, or JWT). If authentication fails, DRF typically returns 401 Unauthorized or 403 Forbidden depending on the authenticator.
  • Authorization (Permissions) answers "Are you allowed to do this?" After authentication, DRF checks permission_classes (such as IsAuthenticated, 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:

  • PUT represents a full replacement of the resource. All required writable fields are expected; omitting required fields typically triggers validation errors.
  • PATCH represents a partial update of the resource. Only the fields provided in the request payload are updated. In DRF serializers, passing partial=True (which UpdateModelMixin.partial_update does automatically for PATCH) skips required checks 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 SQL LIMIT/OFFSET.
  • CursorPagination: Uses an opaque cursor based on a unique, ordered field (like created_at or id). 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 as AnonRateThrottle and UserRateThrottle) and DEFAULT_THROTTLE_RATES (e.g., "100/hour", "1000/day"). When exceeded, DRF returns 429 Too Many Requests with a Retry-After header.
  • 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), and AcceptHeaderVersioning. The active version is available on request.version, and the scheme on request.versioning_scheme.