Skip to content

Instantly share code, notes, and snippets.

@contextmanager
def tenant(value):
"""
Context manager for tenants. Used to set and cleanup tennant.
param, value, can be Tenant object or id.
Using the context context manager
```python
with tenant(1):
Profile.objects.get(pk=1)
class TenantAwareManager(Manager):
def get_queryset(self):
tenant_id = current_tenant_id()
# If the manager was built from a queryset using
# SomeQuerySet.as_manager() or SomeManager.from_queryset(),
# we want to use that queryset instead of TenantAwareQuerySet.
if self._queryset_class != QuerySet:
return super().get_queryset().filter(tenant__id=tenant_id)