-
-
Save seanbehan/e6a9306d6675de93dec5fc355225117b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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