bernardopires / django-tenant-schemas

Tenant support for Django using PostgreSQL schemas.
https://django-tenant-schemas.readthedocs.org/en/latest/
MIT License
1.46k stars 423 forks source link

Automatically run Tenant model queries against the public table without changing the schema #453

Open w0rp opened 7 years ago

w0rp commented 7 years ago

I just had an idea which might fix a problem I have been hitting. Imagine this scenario.

  1. You have some code inside of a tenant, possibly through the middleware, which changes to a particular schema 'foo'.
  2. You use get_tenant_model().objects.all() to get all of the clients.
  3. The query fails, because the Tenant model is associated with a table in the public schema.

I have been hitting this issue a lot, and at the moment the way this issue is fixed in my codebase is to first switch to the public schema before running any queries against the Tenant model, and then switch back to the schema I was using originally. I realised, however, why switch schema at all?

I'm wondering if it's possible to implement a QuerySet class which automatically runs Tenant queries against "<public_schema_name>.<tenant_table_name>", like "public.myapp.tenant". If that were possible, then any queries for the Tenant model would automatically return the right results, without having to change the schema for the connection at all.

If this would cause problems for some users, then perhaps it could be configured with a setting.

It might be possible to implement this by overriding self.query.sql_with_params() for a QuerySet class.

What do you think, @bernardopires?

w0rp commented 7 years ago

I just realised, implementing this might be as simple as setting db_table = '"public"."myapp_tenant"' for the Tenant Model, with perhaps some other considerations.

bernardopires commented 7 years ago

Why do you have to switch to the public schema for that work? AFAIK both the tenant-specific and the public schemas should always be available. See https://github.com/bernardopires/django-tenant-schemas/blob/master/tenant_schemas/postgresql_backend/base.py#L135

w0rp commented 7 years ago

I might try updating to a newer version of django-tenant-schemas, and see if I can take the db_table line away now. I don't know why it worked, I just know it fixed my problem.