Metadata-Version: 2.4
Name: django-cross-tenancy
Version: 0.1.0a2
Summary: Shared-database multi-tenancy for Django with controlled cross-tenant access
Keywords: django,multi-tenancy,tenant,saas,row-level,permissions
Author: Miroslav Zvolský
Author-email: Miroslav Zvolský <zvolsky@seznam.cz>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Requires-Dist: django>=5.2
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# django-cross-tenancy

Shared-database multi-tenancy for Django with **controlled cross-tenant access**.

Schema-per-tenant libraries (such as django-tenants) isolate tenants completely. Some applications need tenants
that are mostly separate but sometimes reach into each other: a relative helps manage another household, a borrowed
item is visible to the borrower, a consultant reads one client's data. django-cross-tenancy keeps all tenants in one
database and decides access per record with plain querysets that you can extend.

> Status: alpha (0.1.0a1). The API may change before 1.0.

## Concepts

- **Tenant**: your concrete model (household, company, team …) subclassing `AbstractTenant`.
- **Membership** (`AbstractMembership`): a user belongs to a tenant with a role: `guest` (view), `member`
  (view and change), `admin` (also manages the tenant and its members). The **active** membership (at most one per
  user, `activate_tenant(user, tenant)`) is the user's active tenant: new records are created there.
- **Grant** (`AbstractTenantGrant`, optional): a user outside the tenant may view, or view and change, all its
  records without being a member.
- **Tenant-owned record** (`TenantModel`): has a `tenant` foreign key and `created_by`. A new record without
  a tenant gets the current user's active tenant; a tenant set explicitly is kept.
- **Access** is a method of the queryset, called with the user explicitly: `user_accessible(user)` (view),
  `user_editable(user)` (change). Override `access_q(user, level)` to widen the reach of a model.

The default manager is never filtered implicitly: admin, forms, migrations, `dumpdata` and background tasks keep
working, and every filtered read names its user.

## Installation

```console
pip install django-cross-tenancy
```

```python
INSTALLED_APPS = [..., 'django_cross_tenancy', ...]
MIDDLEWARE = [..., 'django.contrib.auth.middleware.AuthenticationMiddleware',
              'django_cross_tenancy.middleware.CurrentTenantMiddleware', ...]
CROSS_TENANCY_TENANT_MODEL = 'core.Household'
```

```python
from django_cross_tenancy.models import AbstractMembership, AbstractTenant, AbstractTenantGrant


class Household(AbstractTenant):
    pass


class Membership(AbstractMembership):  # reverse name on the tenant: memberships
    pass


class HouseholdGrant(AbstractTenantGrant):  # reverse name on the tenant: grants
    pass
```

Any user model works; it needs no tenant field. Switch the user's active tenant with
`activate_tenant(user, household)` (the user must be a member).

## Tenant-owned models and overlaps

```python
from django_cross_tenancy.models import VIEW, TenantModel, TenantQuerySet, TenantUniqueConstraint, tenants_for


class ToolQuerySet(TenantQuerySet):
    def access_q(self, user, level):
        q = super().access_q(user, level)
        if level == VIEW:  # a lent tool is visible (read only) to the borrowing household
            lent = Loan.objects.filter(borrower__in=tenants_for(user, VIEW), returned=False)
            q |= Q(pk__in=lent.values('tool'))
        return q


class Tool(TenantModel):
    name = models.CharField(max_length=100)

    objects = ToolQuerySet.as_manager()

    class Meta:
        constraints = [TenantUniqueConstraint(fields=['name'], name='tool_unique_name')]  # per tenant


class Loan(TenantModel):  # tenant = the lender
    tool = models.ForeignKey(Tool, models.CASCADE)
    borrower = models.ForeignKey(Household, models.CASCADE, related_name='+')
    returned = models.BooleanField(default=False)
```

```python
Tool.objects.user_accessible(request.user)   # own, granted and borrowed tools
Tool.objects.user_editable(request.user)     # own and granted with change
```

Prefer `pk__in` subqueries in `access_q` over joins: the result then needs no `distinct()`.

Outside a request (tasks, commands, shell) set the tenant for new records explicitly:

```python
from django_cross_tenancy.context import use_tenant

with use_tenant(household, user):
    Tool.objects.create(name='drill')
```

`bulk_create` bypasses `save()`: set `tenant` yourself.

## Global and private records in one table

A code list can hold global records shared by everyone and private records each tenant adds:

```python
class MeterType(TenantModel):
    global_and_private = True  # tenant becomes nullable: null = global record

    name = models.CharField(max_length=100)

    class Meta:
        constraints = [TenantUniqueConstraint(fields=['name'], name='metertype_unique_name')]
```

- `user_accessible(user)` returns the tenant's records **and** the global ones (`tenant IS NULL`); only models with
  `global_and_private = True` pay for the extra condition.
- Only superusers change or delete global records.
- New records: ordinary users always create in their active tenant; a superuser chooses in the admin form between
  the active tenant and an empty value (global). In code, `use_tenant(None)` (or a superuser's request) keeps
  a record without a tenant global; ordinary `TenantModel`s still refuse to be saved without a tenant.

## Unique values: `TenantUniqueConstraint`

`TenantUniqueConstraint(fields=[...], name=...)` keeps values unique among the records a user sees together:

- within one tenant: no tenant has "Gas meter" twice,
- with `global_and_private`, also between a tenant's records and the global ones: a private record may not repeat
  a global one, a global record may not repeat another global one or any private one,
- two tenants may each have a record with the same values ("Workshop gas meter" in both).

Don't list `tenant` in `fields`; the constraint adds it. On PostgreSQL the database enforces it as an exclusion
constraint (the tenant as an integer range, null = unbounded, so a global record overlaps every tenant), which
needs the `btree_gist` extension created first:

```python
from django.contrib.postgres.operations import BtreeGistExtension

class Migration(migrations.Migration):
    operations = [BtreeGistExtension(), ...]  # before the migration that adds the constraint
```

Validation (admin forms, `full_clean`) checks the same rule with clear messages, also when the form leaves `tenant`
out (the admin mixin sets the tenant before validation). Other databases get no constraint in the schema and rely on
validation only. Like `unique`, null values never clash.

## Admin

```python
from django_cross_tenancy.admin import ManagedTenantAdminMixin, TenantAdminMixin, TenantManagerInlineMixin


@admin.register(Tool)
class ToolAdmin(TenantAdminMixin, admin.ModelAdmin):
    ...
```

- `TenantAdminMixin`: list and object permissions follow `user_accessible` / `user_editable`; new records go to the
  user's active tenant (inline rows to their parent's tenant); relation choices are narrowed to records the user may
  see.
  For `global_and_private` models, superusers get the tenant field with two choices (the record's or the active
  tenant, or empty = global); other users see it read only.
- `ManagedTenantAdminMixin`: for the tenant model; users see their tenants, only administrators change them, the
  creator of a tenant becomes its administrator.
- `TenantManagerInlineMixin`: memberships and grants inlines, editable by the tenant's administrators only.

The mixins only narrow what the admin allows: model permissions still apply.

## Development

```console
uv run --package django-cross-tenancy pytest
CROSS_TENANCY_TEST_POSTGRES=cross_tenancy uv run --package django-cross-tenancy pytest  # PostgreSQL (PGHOST, PGUSER …)
```

## License

MIT
