HH/apps/core/managers.py

32 lines
975 B
Python

"""
Tenant-aware managers and querysets for multi-tenancy
"""
from django.db import models
class TenantQuerySet(models.QuerySet):
"""QuerySet that automatically filters by current tenant."""
def for_tenant(self, hospital):
"""Filter records for specific hospital."""
return self.filter(hospital=hospital)
def for_current_tenant(self, request):
"""Filter records for current request's tenant hospital."""
if hasattr(request, 'tenant_hospital') and request.tenant_hospital:
return self.filter(hospital=request.tenant_hospital)
return self
class TenantManager(models.Manager):
"""Manager that uses TenantQuerySet."""
def get_queryset(self):
return TenantQuerySet(self.model, using=self._db)
def for_tenant(self, hospital):
return self.get_queryset().for_tenant(hospital)
def for_current_tenant(self, request):
return self.get_queryset().for_current_tenant(request)