Skip to content

Instantly share code, notes, and snippets.

@dlederle
Created April 16, 2021 19:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dlederle/8ab86cbeecb08a0500e28f0dc4e1bd5e to your computer and use it in GitHub Desktop.
Save dlederle/8ab86cbeecb08a0500e28f0dc4e1bd5e to your computer and use it in GitHub Desktop.
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)
return TenantAwareQuerySet(self.model, using=self._db).filter(
tenant__id=tenant_id
)
class TenantAwareQuerySet(QuerySet):
def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
objs = list(objs)
for o in objs:
o.tenant = current_tenant()
super().bulk_create(objs, batch_size, ignore_conflicts)
def as_manager(cls):
manager = TenantAwareManager.from_queryset(cls)()
manager._built_with_as_manager = True
return manager
as_manager.queryset_only = True
as_manager = classmethod(as_manager)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment