Multi-Tenancy

Django School-Scoped Query

Scopes student records to the authenticated user’s current school context.

PYTHON Django Advanced

Problem

Engineering context

Shared applications must prevent school records from crossing organisational boundaries.

Solution boundary

Filter the queryset by trusted school context and enforce permission separately.

students/views.pyPYTHON
def get_queryset(self):
    school = self.request.user.current_school
    if not self.request.user.has_perm("students.view_student"):
        raise PermissionDenied
    return Student.objects.filter(school=school)

How it works

How it works

Scoping reduces the accessible dataset before object lookup.

Security considerations

Security considerations

Query filtering alone is insufficient; validate membership and change permission on writes.

Performance considerations

Performance considerations

Index school foreign keys and frequent ordering columns.

Tradeoffs

Tradeoffs

Context propagation must also cover background tasks and exports.

Testing notes

Testing notes

Test unauthenticated, unauthorized and cross-school access.

Limitations

Limitations

Illustrative public-safe example; adapt the boundary and domain rules to the actual application.

Engineering evidence

Connected design context

Architecture

Related evidence

Django

Engineering insights

Practical notes, occasionally.

Double opt-in, no list selling, and unsubscribe anytime.