NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior78 views

Вы хорошо отметили важность безопасности и корректности данных. Расскажите, как бы вы реализовали фильтрацию по владельцу в Django ORM, чтобы избежать таких утечек?

Practice

Asked at

AI answer

I would restrict the queryset to the current user on the server, rather than trusting owner_id supplied by the client. For example:

from django.shortcuts import get_object_or_404

class DocumentDetailView(DetailView):
    def get_queryset(self):
        return Document.objects.filter(owner=self.request.user)

# In the API:
document = get_object_or_404(
    Document.objects.filter(owner=request.user),
    pk=document_id,
)

That way, another user's object won't appear in either the list or the detail request. The same restriction should be applied to updates and deletions, including nested resources. When creating an object, the owner should be assigned from request.user, rather than taken from the request body. I would also add tests for access to other users' objects and check all data-access paths, including background tasks and admin/API endpoints.