A DRF API that starts with permission_classes = [IsAuthenticated] and an auto-generated ModelSerializer works fine for an MVP. The trouble shows up six months later, once roles, shared objects between users, and nested serializers that silently pull half the database on every request have piled up. What looked like an implementation detail turns into an architectural problem.
The view-level permission trap
DRF splits permissions into two families that get confused constantly: global permissions (has_permission), checked before the view is even reached, and object-level permissions (has_object_permission), checked only on actions that fetch a specific instance (retrieve, update, destroy).
The classic trap: writing a permission that correctly checks ownership on retrieve, while forgetting that list never goes through has_object_permission at all. The queryset behind list has to do its own filtering, or the object permission only ever protects part of the endpoints.
from rest_framework.permissions import BasePermission
class IsOwnerOrReadOnly(BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in ("GET", "HEAD", "OPTIONS"):
return True
return obj.owner_id == request.user.id
This permission protects retrieve, update, destroy. It does nothing for list: if the view's get_queryset() returns Document.objects.all(), any authenticated user sees every document belonging to every other user, even though they can't edit them. It's a silent data leak, not a visible 403 you'd catch in manual testing.
class DocumentViewSet(ModelViewSet):
permission_classes = [IsAuthenticated, IsOwnerOrReadOnly]
def get_queryset(self):
user = self.request.user
if user.is_staff:
return Document.objects.all()
return Document.objects.filter(owner=user)
The rule worth keeping: an object permission protects actions on a single instance, never a collection. Filtering a collection is the queryset's job, not the permission class's.
Compose permissions instead of stacking them
Once the rules get more complex (owner OR team member OR admin role), it's tempting to write one permission class with a cascade of if statements. That reads poorly fast. DRF lets permissions be composed with &, | and ~:
permission_classes = [IsAuthenticated & (IsOwner | IsTeamMember | IsAdminRole)]
Each class stays independently testable, and the combination logic is explicit right in the view declaration instead of buried in a method.
The nested serializer / N+1 trap
A ModelSerializer with nested fields (a serializers.SerializerMethodField, or a child serializer referenced through a ForeignKey) fires one SQL query per serialized object whenever the view's queryset doesn't preload the relation. It's the exact same N+1 problem familiar from the ORM, just wearing an API costume: invisible locally with ten fixture rows, devastating in production with ten thousand records.
class CommentSerializer(serializers.ModelSerializer):
author = serializers.SerializerMethodField()
class Meta:
model = Comment
fields = ["id", "body", "author"]
def get_author(self, obj):
return {"id": obj.author.id, "name": obj.author.get_full_name()}
On a list of a hundred comments, DRF calls get_author a hundred times, and each call touches obj.author, which triggers a query unless the relation was preloaded. The fix happens at the queryset level, not in the serializer:
class CommentViewSet(ModelViewSet):
serializer_class = CommentSerializer
queryset = Comment.objects.select_related("author").all()
select_related emits a SQL JOIN for ForeignKey and OneToOne relations. For ManyToMany or reverse ForeignKey relations (say, preloading all the tags on an article), you need prefetch_related, which runs a separate query, but just one, for the whole queryset instead of one per object.
queryset = Article.objects.prefetch_related("tags", "comments__author")
The __ in comments__author preloads two levels at once: the article's comments, then each comment's author, in two queries total instead of 1 + N + N.
Diagnose before fixing
Before sprinkling select_related everywhere on a hunch, measure first. django-silk or the django-debug-toolbar middleware show the query count per endpoint. From the command line, turning on Django's SQL logger gives the same signal without an extra dependency:
LOGGING = {
"version": 1,
"handlers": {"console": {"class": "logging.StreamHandler"}},
"loggers": {
"django.db.backends": {
"handlers": ["console"],
"level": "DEBUG",
},
},
}
An endpoint that goes from 1 query to 101 queries when the result set grows from one row to a hundred is the textbook N+1 signature. The goal isn't zero extra queries, it's a query count that stays constant regardless of result size.
Read serializers and write serializers should not be the same class
A common trap is reusing one ModelSerializer for both reading (GET) and writing (POST/PATCH). As soon as the API has computed fields, sensitive fields the client should never be able to set (is_verified, role), or nested representations on read but plain IDs on write, a single shared serializer turns into an awkward pile of read_only_fields.
class UserPublicSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "username", "avatar_url"]
class UserWriteSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["username", "email", "password"]
extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data):
return User.objects.create_user(**validated_data)
Splitting the two keeps each class small and explicit, and more importantly prevents a sensitive field (role, is_staff) from accidentally becoming writable just because it had to be present in a serializer shared with the read path. It's also a security concern: a field that's absent from a write serializer simply can't be injected through a malicious payload, whereas a forgotten read_only_fields entry on a later field addition reopens the hole.
Permissions that vary by action
Another common mistake is declaring a single static permission_classes list on the whole ViewSet, when access rules often differ by action: creating a document might be open to any authenticated user, while deleting one should be restricted to the owner or an admin. Forcing one shared permission pushes developers toward a class that inspects view.action itself, which just reimplements inside the permission the routing logic DRF already provides.
class DocumentViewSet(ModelViewSet):
def get_permissions(self):
if self.action in ("create",):
return [IsAuthenticated()]
if self.action in ("update", "partial_update", "destroy"):
return [IsAuthenticated(), IsOwnerOrAdmin()]
return [IsAuthenticated(), IsOwnerOrReadOnly()]
get_permissions() runs on every request and must return instances, not classes, which is why each name is followed by (). This keeps each permission class small and independently testable, and centralizes the per-action routing logic in the same place as the rest of the ViewSet's behavior, instead of scattering it across conditionals inside individual permissions.
Cross-field validation: validate() versus validate_<field>
A DRF serializer offers two validation levels that are easy to misuse. validate_<field_name> validates one field in isolation, with no access to the rest of the payload. validate() receives the full dictionary of already field-validated data, and it's the only correct place for a rule that depends on more than one field at once.
class BookingSerializer(serializers.ModelSerializer):
class Meta:
model = Booking
fields = ["id", "start_date", "end_date", "room"]
def validate_start_date(self, value):
if value < timezone.now().date():
raise serializers.ValidationError("Start date cannot be in the past.")
return value
def validate(self, attrs):
if attrs["end_date"] <= attrs["start_date"]:
raise serializers.ValidationError(
{"end_date": "End date must be after the start date."}
)
return attrs
A common mistake is trying to compare start_date and end_date inside validate_end_date: at that point, there's no guarantee start_date has already been validated and made available, since DRF doesn't guarantee an execution order between per-field validators. A cross-field rule should always live in validate(), never in a validate_<field> method that reaches into self.initial_data to work around the limitation, which just reintroduces unvalidated data into a method meant to only ever see clean data.
When the easy fix isn't enough
select_related and prefetch_related solve N+1 for a given endpoint, but an API with serializers nested several levels deep (an article with its comments, each comment with its reactions, each reaction with its author) eventually needs either strict pagination combined with targeted preloading per level, or an architectural shift toward dedicated endpoints that expose flatter views. At that point, stacking more nested prefetch_related calls is a signal to rethink the shape of the exposed resource, not to keep optimizing the query.
For permissions, once rules start depending on multiple organizations, hierarchical roles, or temporary delegations, a dedicated library such as django-guardian for per-object permissions, or an externalized authorization layer, becomes more appropriate than a pile of homemade BasePermission classes.
Takeaway
DRF object permissions never protect a collection; list filtering belongs in the queryset. N+1 is diagnosed by comparing SQL query count against result size, and fixed with select_related/prefetch_related at the view's queryset level, never inside the serializer. Splitting read and write serializers keeps a sensitive field from becoming writable by accident.
