[hypequery](https://hypequery.com/) › ClickHouse with Django: Governed Analytics in Your Views | hypequery
Index for agents: https://hypequery.com/llms.txt
Canonical page: https://hypequery.com/clickhouse-django

> Query ClickHouse from Django with shared, tenant-scoped definitions. Define measures once in Python, call them from views, and keep the ORM for app data.

[Open sourceApache 2.0](https://github.com/hypequery/hypequery)

ClickHouse Django

# Use ClickHouse from Django without raw SQL in every view

The Django ORM is built for your transactional database. For analytics in ClickHouse, hypequery gives your views and tasks named measures and dimensions, scoped to the signed-in customer, from definitions you write once in Python.

[Django guide ](https://hypequery.com/docs/python/django)[Python quick start](https://hypequery.com/docs/quick-start#python)

Works in

Sync and async views

Tenant from

request.user

Setup

One app, one middleware

## The ORM doesn’t fit ClickHouse

Django’s ORM expects transactions, migrations, and row updates. Analytics on ClickHouse is aggregations over billions of rows, so teams fall back to raw SQL strings.

## Raw SQL spreads through views

Each view and Celery task writes its own revenue query. They drift, and none of them is reviewed as a definition.

## Tenant scoping is manual

Every query has to remember the organisation filter. The one that forgets shows one customer another customer’s numbers.

Views and tasks

## Query named measures from any view

Add the app and middleware, point `HYPEQUERY` at your datasets, and every view gets `request.analytics`, a client already scoped to the signed-in user’s organisation. The query is planned from your dataset, with the tenant filter added for you.

- Sync views get the sync client; async views get the async one, from the same attribute
- `manage.py check` validates the setting without connecting to ClickHouse
- A query without a tenant fails instead of reading every customer
- Celery tasks use `get_client()` and bind the tenant explicitly

views.py

### A tenant-scoped Django view

analytics/views.py

```
# settings.py
INSTALLED_APPS = [..., "hypequery.contrib.django"]
MIDDLEWARE = [
    ...,
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "hypequery.contrib.django.HypequeryMiddleware",
]
# The ClickHouse connection comes from CLICKHOUSE_URL.
HYPEQUERY = {
    "REGISTRY": "analytics.datasets.registry",  # your datasets
    "TENANT": "analytics.tenancy.tenant_for_request",  # request -> org
}

# analytics/tenancy.py
def tenant_for_request(request):
    if request.user.is_authenticated:
        return request.user.organization_id
    return None

# analytics/views.py
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse

@login_required
def revenue_by_status(request):
    # Already scoped to the signed-in user's organization
    result = request.analytics.execute(
        "orders", {"dimensions": ["status"], "measures": ["revenue"]}
    )
    return JsonResponse({"data": list(result.data)})
```

The client is built on first use, closed at exit, and rebuilt in each forked worker. Results are plain dicts, ready for JsonResponse or a template.

Tasks and commands

## The same numbers in Celery, commands and exports

Outside a request, `get_client()` returns the process-wide client and you bind the tenant explicitly. Reports, exports and scheduled jobs use the same definitions as your views, and `to_pandas()` turns results into typed DataFrames.

The client connects on its first query, is closed when the process exits, and is rebuilt in each forked worker, so gunicorn and Celery prefork pools are safe.

For typed React hooks or the MCP bridge, mount hypequery’s HTTP endpoints in your URLconf with `urls(api)`. You don’t run a second service, and the session API uses your Django login.

tasks.py

### A tenant-scoped Celery task

analytics/tasks.py

```
# analytics/tasks.py — Celery, management commands, scripts
from celery import shared_task
from hypequery.contrib.django import get_client
from hypequery.datasets import tenant

@shared_task
def monthly_report(organization_id):
    # The same definitions and process-wide client the views use;
    # outside a request, the tenant is passed explicitly.
    client = get_client().for_tenant(tenant(organization_id))
    result = client.execute(
        "orders",
        {"dimensions": ["status"], "measures": ["revenue"], "by": "month"},
    )
    return result.to_pandas().to_csv(index=False)
```

Results convert to a typed DataFrame for exports.

Where teams usually get stuck

## Questions teams ask

### Django analytics dashboard

Views return measures by dimension and time grain, scoped to the user’s organisation.

### Celery jobs on ClickHouse

Reports and exports use the same definitions as the app, with an explicit tenant for each run.

### Can the Django ORM query ClickHouse?

Through a third-party database backend. The community django-clickhouse-backend package (2.0 on PyPI, checked 14 November 2026) lets Django models target ClickHouse. hypequery takes the other route. The ORM stays on your transactional database, and analytics go through named, tenant-scoped measures.

### Is there a Django integration?

Yes: `hypequery.contrib.django` adds settings, a system check, `request.analytics` middleware, and clients for tasks and commands.

Examples

## Runnable examples

Every example runs against the same seeded ClickHouse dataset. Scaffold one with `npx @hypequery/cli create <slug> -y`, or browse the [full list](https://hypequery.com/examples).

[Example · Python](https://hypequery.com/examples/django-analytics)

### [Django analytics on ClickHouse: ORM for app data, typed datasets for metrics](https://hypequery.com/examples/django-analytics)

[Keep your Django models in SQLite or Postgres and serve ClickHouse analytics from typed hypequery datasets, scoped to request.user's organization.](https://hypequery.com/examples/django-analytics)

[PythonDjangoClickHouseAnalytics APIMulti-tenantSaaS analytics](https://hypequery.com/examples/django-analytics)

[Open example](https://hypequery.com/examples/django-analytics)

Further reading

## Go deeper where it actually helps

### [Django guide](https://hypequery.com/docs/python/django)

[Settings, middleware, async views, and tasks.](https://hypequery.com/docs/python/django)

[Open guide](https://hypequery.com/docs/python/django)

### [Python quick start](https://hypequery.com/docs/quick-start#python)

[Install hypequery and define your first dataset.](https://hypequery.com/docs/quick-start#python)

[Open guide](https://hypequery.com/docs/quick-start#python)

### [Multi-tenancy](https://hypequery.com/docs/python/datasets/multi-tenancy)

[Tenant keys and tenant-bound clients.](https://hypequery.com/docs/python/datasets/multi-tenancy)

[Open guide](https://hypequery.com/docs/python/datasets/multi-tenancy)

### [pandas, Polars and Arrow](https://hypequery.com/docs/python/dataframes)

[Typed DataFrames for reports and exports.](https://hypequery.com/docs/python/dataframes)

[Open guide](https://hypequery.com/docs/python/dataframes)

Related pillars

[ClickHouse SQLAlchemy](https://hypequery.com/clickhouse-sqlalchemy)[ClickHouse with Python](https://hypequery.com/clickhouse-python)[ClickHouse with Flask](https://hypequery.com/clickhouse-flask)[Python multi-tenancy](https://hypequery.com/clickhouse-python-multi-tenant)[FastAPI + React](https://hypequery.com/fastapi-react-analytics)

Next step

## Replace one raw SQL view

Define the dataset behind one Django report, then swap its SQL for a scoped dataset query.

Open source, and it runs in your own backend. Want it hosted?

[Django guide ](https://hypequery.com/docs/python/django)[Python quick start](https://hypequery.com/docs/quick-start#python)
