Files
RosterChief/clubmanager/base.py
Bernard Siebens 72e7b5e070 feat(tenancy): resolve active club from request subdomain
Add row-based multi-tenancy plumbing keyed on Club as the tenant root:

- ClubTenantMiddleware maps the request's subdomain to a Club by slug,
  storing it on request.club and in a contextvar so service-layer code
  and management commands can read it via get_current_club(). Resolution
  honours CLUBMANAGER_BASE_DOMAIN (e.g. ajax-united.clubmanager.app),
  falling back to generic slug.example.com hosts, and ignores the bare
  base domain, www, and unknown slugs.
- Club gains a unique slug (auto-derived from name on save) plus a
  ClubManager.current() accessor for the active tenant.
- ClubScopedModel gets a TenantQuerySet (.for_club()/.current()) and
  auto-fills club from the active context on save.

Contextvar helpers live in club.tenancy; Club is imported lazily there
and in clubmanager.base to avoid an import cycle with club.models.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 15:32:05 +02:00

43 lines
1.0 KiB
Python

import uuid
from typing import TYPE_CHECKING
from django.db import models
from club.tenancy import require_current_club
if TYPE_CHECKING:
from club.models import Club
class TenantQuerySet(models.QuerySet):
def for_club(self, club: Club):
return self.filter(club=club)
def current(self):
return self.filter(club=require_current_club())
class UUIDModel(models.Model):
"""Abstract base class giving every model a UUID primary key"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Meta:
abstract = True
class ClubScopedModel(UUIDModel):
"""Abstract base for entities owned by a single club (tenant root)."""
club = models.ForeignKey("club.Club", on_delete=models.CASCADE, related_name="%(class)ss")
objects = TenantQuerySet.as_manager()
class Meta:
abstract = True
def save(self, *args, **kwargs):
if self.club_id is None:
self.club = require_current_club()
super().save(*args, **kwargs)