Best way to use tenant

Hello,

I currently have a saas application, I have over 1000 clients.
After using django-tenants-schemas I chose the approach of having data in a single schema and each model having tenant_id, for reasons of scalability.

After some studies I saw this lecture by Armin Ronacher, he shows an approach using sqlalchemy where he sets the tenant by an ORM event:

image

Based on this code, can I do anything specifically with django?
My approach was this:

@Field.register_lookup
class CurrentTenant(models.Lookup):
    lookup_name = 'ct'

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        tenant = get_current_tenant()  # set tenant in middleware
        params = lhs_params

        return '%s = %s' % (lhs, str(tenant.id)), params


class TenantManager(models.Manager):
    queryset_class = models.QuerySet

    def get_queryset(self):
        return self.queryset_class(self.model, using=self._db).filter(
            tenant__id__ct=0)

is it correct to do this?

1 Like

It sounds like django-scopes might either fit your problem, or will at least give you a starting point on the implementation.

1 Like

I started this project, take some ideas for django-scopes and django-tenants, but depending on the logged-in user, to my project case, it is helping :slight_smile: