django-multitenant icon indicating copy to clipboard operation
django-multitenant copied to clipboard

Possible for users to run queries against a different tenant_id?

Open tabdon opened this issue 4 years ago • 1 comments

I have the model design below. Here is the logic at the heart of my question:

  • teams can access "marketplace" courses that are available to all teams
  • teams can create their own courses that are private to them
class Team(TenantModel):
    tenant_id = 'id'
    name = models.CharField(max_length=50)

class User(TenantModelMixin, AbstractBaseUser, PermissionsMixin):
    team = models.ForeignKey(Team, on_delete=models.PROTECT)
    tenant_id = 'team_id'
    email = models.EmailField(max_length=100, unique=True, db_index=True)
    # .... additional fields

class Course(TenantModel):
    team = models.ForeignKey(Team, on_delete=models.PROTECT)
    tenant_id = 'team_id'
    title = models.CharField(max_length=200)
    # .... additional fields

The middleware:

class MultitenantMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user and not request.user.is_anonymous:
            set_current_tenant(request.user.team)
        return self.get_response(request)

What is the best way to structure the DB and/or middleware to support this use case?

tabdon avatar Nov 02 '20 06:11 tabdon

My rough guess would be for the Course model not to inherit from TenantModel since it has FK to Team which is TenantModel anyway.

grucha avatar Jun 08 '21 07:06 grucha