| 1 |
--- |
| 2 |
title: Upgrading to Direct Foreign Keys |
| 3 |
description: Step-by-step guide for upgrading existing projects from generic object permissions to direct foreign key based permissions while preserving all data. |
| 4 |
--- |
| 5 |
|
| 6 |
# Upgrading to Direct Foreign Keys |
| 7 |
|
| 8 |
This guide covers the process of migrating a **running, production project** |
| 9 |
from django-guardian's default generic permission tables to the |
| 10 |
[direct foreign key](performance.md#direct-foreign-keys) approach — without |
| 11 |
losing any existing permission data. |
| 12 |
|
| 13 |
## Why Migrate? |
| 14 |
|
| 15 |
Django-guardian's default `UserObjectPermission` and `GroupObjectPermission` |
| 16 |
models use Django's contenttypes framework to store a **generic relation** |
| 17 |
(`content_type` + `object_pk`). This design is flexible, but it has a cost: |
| 18 |
|
| 19 |
- `object_pk` is stored as a `CharField`, so every query must cast or compare |
| 20 |
strings instead of using native primary key types. |
| 21 |
- There is no real database-level foreign key, meaning the database cannot |
| 22 |
enforce referential integrity or use foreign key indexes efficiently. |
| 23 |
- As the permission tables grow, queries that filter by `content_type` and |
| 24 |
`object_pk` become increasingly expensive — especially on tables with |
| 25 |
millions of rows. |
| 26 |
|
| 27 |
For **high-volume projects** — or any project where object permission checks |
| 28 |
appear in hot paths — switching to direct foreign keys can yield a dramatic |
| 29 |
improvement in query performance and data integrity. |
| 30 |
|
| 31 |
!!! tip "See Also" |
| 32 |
[Performance Tuning — Direct Foreign Keys](performance.md#direct-foreign-keys) |
| 33 |
for an overview of the direct foreign key approach. |
| 34 |
|
| 35 |
--- |
| 36 |
|
| 37 |
## Operational Safety |
| 38 |
|
| 39 |
!!! danger "Do Not Run This Migration on a Live System" |
| 40 |
This migration **must not** run while the application is actively serving |
| 41 |
requests that create, modify, or delete object permissions. If a |
| 42 |
permission is assigned or removed in the generic table *during* the data |
| 43 |
copy, a **race condition** occurs: the new record will not be copied to |
| 44 |
the direct table, resulting in **silently lost permissions**. |
| 45 |
|
| 46 |
Before starting the migration, complete **all three** of the following |
| 47 |
pre-flight checks: |
| 48 |
|
| 49 |
### 1. Enable Maintenance Mode |
| 50 |
|
| 51 |
Take the application offline so that end users cannot trigger any permission |
| 52 |
changes. A convenient way to do this is the |
| 53 |
[django-maintenance-mode](https://github.com/fabiocaccamo/django-maintenance-mode) |
| 54 |
package: |
| 55 |
|
| 56 |
```bash |
| 57 |
pip install django-maintenance-mode |
| 58 |
python manage.py maintenance_mode on |
| 59 |
``` |
| 60 |
|
| 61 |
### 2. Stop Background Workers |
| 62 |
|
| 63 |
Stop or pause **all** Celery workers, cron jobs, management command schedules, |
| 64 |
and any other background tasks that may call `assign_perm`, `remove_perm`, or |
| 65 |
modify object permissions in any way. Any write to the generic permission |
| 66 |
tables during the migration window can cause data inconsistency. |
| 67 |
|
| 68 |
### 3. Take a Full Database Backup |
| 69 |
|
| 70 |
Before touching any data, create a complete database backup. If anything goes |
| 71 |
wrong during the migration, you need to be able to restore to the |
| 72 |
pre-migration state. |
| 73 |
|
| 74 |
```bash |
| 75 |
# PostgreSQL example |
| 76 |
pg_dump -Fc mydb > pre_direct_fk_migration.dump |
| 77 |
``` |
| 78 |
|
| 79 |
--- |
| 80 |
|
| 81 |
## Step 1 — Define the Direct Foreign Key Models |
| 82 |
|
| 83 |
For each model that has object permissions, create two new models that inherit |
| 84 |
from `UserObjectPermissionBase` and `GroupObjectPermissionBase`. **Set |
| 85 |
`enabled = False`** so that django-guardian continues to use the generic tables |
| 86 |
while the new tables are being created and populated. |
| 87 |
|
| 88 |
```python |
| 89 |
# myapp/models.py |
| 90 |
|
| 91 |
from django.db import models |
| 92 |
from guardian.models import UserObjectPermissionBase, GroupObjectPermissionBase |
| 93 |
|
| 94 |
|
| 95 |
class Project(models.Model): |
| 96 |
name = models.CharField(max_length=128, unique=True) |
| 97 |
|
| 98 |
class Meta: |
| 99 |
permissions = ( |
| 100 |
("view_project", "Can view project"), |
| 101 |
("manage_project", "Can manage project"), |
| 102 |
) |
| 103 |
|
| 104 |
|
| 105 |
class ProjectUserObjectPermission(UserObjectPermissionBase): |
| 106 |
content_object = models.ForeignKey( |
| 107 |
Project, on_delete=models.CASCADE, related_name="user_object_permissions" |
| 108 |
) |
| 109 |
enabled = False # Keep using generic tables for now |
| 110 |
|
| 111 |
|
| 112 |
class ProjectGroupObjectPermission(GroupObjectPermissionBase): |
| 113 |
content_object = models.ForeignKey( |
| 114 |
Project, on_delete=models.CASCADE, related_name="group_object_permissions" |
| 115 |
) |
| 116 |
enabled = False # Keep using generic tables for now |
| 117 |
``` |
| 118 |
|
| 119 |
Now generate and apply the migration to create the new tables: |
| 120 |
|
| 121 |
```bash |
| 122 |
python manage.py makemigrations myapp |
| 123 |
python manage.py migrate myapp |
| 124 |
``` |
| 125 |
|
| 126 |
At this point, the new tables exist but are empty, and django-guardian is |
| 127 |
still reading from and writing to the generic tables. |
| 128 |
|
| 129 |
--- |
| 130 |
|
| 131 |
## Step 2 — Data Migration |
| 132 |
|
| 133 |
Create a data migration that copies every existing permission from the generic |
| 134 |
tables into the new direct tables. |
| 135 |
|
| 136 |
```bash |
| 137 |
python manage.py makemigrations myapp --empty -n migrate_to_direct_fk |
| 138 |
``` |
| 139 |
|
| 140 |
Then edit the generated file: |
| 141 |
|
| 142 |
```python |
| 143 |
# myapp/migrations/XXXX_migrate_to_direct_fk.py |
| 144 |
|
| 145 |
from django.db import migrations |
| 146 |
|
| 147 |
|
| 148 |
def forwards(apps, schema_editor): |
| 149 |
ContentType = apps.get_model("contenttypes", "ContentType") |
| 150 |
UserObjectPermission = apps.get_model("guardian", "UserObjectPermission") |
| 151 |
GroupObjectPermission = apps.get_model("guardian", "GroupObjectPermission") |
| 152 |
|
| 153 |
Project = apps.get_model("myapp", "Project") |
| 154 |
ProjectUserObjPerm = apps.get_model("myapp", "ProjectUserObjectPermission") |
| 155 |
ProjectGroupObjPerm = apps.get_model("myapp", "ProjectGroupObjectPermission") |
| 156 |
|
| 157 |
project_ct = ContentType.objects.get_for_model(Project) |
| 158 |
|
| 159 |
# --- User permissions --- |
| 160 |
user_perms = UserObjectPermission.objects.filter(content_type=project_ct) |
| 161 |
|
| 162 |
BATCH_SIZE = 2000 |
| 163 |
batch = [] |
| 164 |
for perm in user_perms.iterator(): |
| 165 |
batch.append( |
| 166 |
ProjectUserObjPerm( |
| 167 |
permission_id=perm.permission_id, |
| 168 |
user_id=perm.user_id, |
| 169 |
# Cast object_pk to the target model's PK type. |
| 170 |
content_object_id=int(perm.object_pk), # see warning below |
| 171 |
) |
| 172 |
) |
| 173 |
if len(batch) >= BATCH_SIZE: |
| 174 |
ProjectUserObjPerm.objects.bulk_create(batch, ignore_conflicts=True) |
| 175 |
batch = [] |
| 176 |
|
| 177 |
if batch: |
| 178 |
ProjectUserObjPerm.objects.bulk_create(batch, ignore_conflicts=True) |
| 179 |
|
| 180 |
# --- Group permissions --- |
| 181 |
group_perms = GroupObjectPermission.objects.filter(content_type=project_ct) |
| 182 |
|
| 183 |
batch = [] |
| 184 |
for perm in group_perms.iterator(): |
| 185 |
batch.append( |
| 186 |
ProjectGroupObjPerm( |
| 187 |
permission_id=perm.permission_id, |
| 188 |
group_id=perm.group_id, |
| 189 |
content_object_id=int(perm.object_pk), # see warning below |
| 190 |
) |
| 191 |
) |
| 192 |
if len(batch) >= BATCH_SIZE: |
| 193 |
ProjectGroupObjPerm.objects.bulk_create(batch, ignore_conflicts=True) |
| 194 |
batch = [] |
| 195 |
|
| 196 |
if batch: |
| 197 |
ProjectGroupObjPerm.objects.bulk_create(batch, ignore_conflicts=True) |
| 198 |
|
| 199 |
|
| 200 |
def backwards(apps, schema_editor): |
| 201 |
""" |
| 202 |
Reverse migration: remove all records from direct tables. |
| 203 |
The generic table records are still intact. |
| 204 |
""" |
| 205 |
ProjectUserObjPerm = apps.get_model("myapp", "ProjectUserObjectPermission") |
| 206 |
ProjectGroupObjPerm = apps.get_model("myapp", "ProjectGroupObjectPermission") |
| 207 |
ProjectUserObjPerm.objects.all().delete() |
| 208 |
ProjectGroupObjPerm.objects.all().delete() |
| 209 |
|
| 210 |
|
| 211 |
class Migration(migrations.Migration): |
| 212 |
|
| 213 |
dependencies = [ |
| 214 |
("myapp", "XXXX_previous_migration"), # replace with actual name |
| 215 |
("guardian", "0001_initial"), |
| 216 |
("contenttypes", "0002_remove_content_type_name"), |
| 217 |
] |
| 218 |
|
| 219 |
operations = [ |
| 220 |
migrations.RunPython(forwards, backwards), |
| 221 |
] |
| 222 |
``` |
| 223 |
|
| 224 |
!!! warning "Primary Key Type Casting" |
| 225 |
The generic table stores `object_pk` as a **string**. You must cast it to |
| 226 |
the target model's actual primary key type when building the direct |
| 227 |
record: |
| 228 |
|
| 229 |
| Target PK type | Cast | |
| 230 |
|---|---| |
| 231 |
| `AutoField` / `BigAutoField` / `IntegerField` | `int(perm.object_pk)` | |
| 232 |
| `UUIDField` | `uuid.UUID(perm.object_pk)` | |
| 233 |
| `CharField` | No cast needed — use `perm.object_pk` directly | |
| 234 |
|
| 235 |
Mismatched types will cause `IntegrityError` or silent data corruption. |
| 236 |
|
| 237 |
!!! tip "Multiple Models" |
| 238 |
If you have more than one model with object permissions (e.g. `Project`, |
| 239 |
`Task`, `Document`), you need to repeat the direct model pair and the |
| 240 |
migration block **for each model**. You can place all copies in the same |
| 241 |
`RunPython` function to run them in a single migration. |
| 242 |
|
| 243 |
Apply the migration: |
| 244 |
|
| 245 |
```bash |
| 246 |
python manage.py migrate myapp |
| 247 |
``` |
| 248 |
|
| 249 |
--- |
| 250 |
|
| 251 |
## Step 3 — Enable the Direct Models |
| 252 |
|
| 253 |
Now that the data is in place, remove the `enabled = False` flag (or set it to |
| 254 |
`True`) so that django-guardian starts using the direct tables for all future |
| 255 |
reads and writes: |
| 256 |
|
| 257 |
```python |
| 258 |
# myapp/models.py |
| 259 |
|
| 260 |
class ProjectUserObjectPermission(UserObjectPermissionBase): |
| 261 |
content_object = models.ForeignKey( |
| 262 |
Project, on_delete=models.CASCADE, related_name="user_object_permissions" |
| 263 |
) |
| 264 |
# enabled = False ← removed |
| 265 |
|
| 266 |
|
| 267 |
class ProjectGroupObjectPermission(GroupObjectPermissionBase): |
| 268 |
content_object = models.ForeignKey( |
| 269 |
Project, on_delete=models.CASCADE, related_name="group_object_permissions" |
| 270 |
) |
| 271 |
# enabled = False ← removed |
| 272 |
``` |
| 273 |
|
| 274 |
Since `enabled` is a **class attribute** and not a database field, no new |
| 275 |
migration is required. A deployment (application restart) is enough for the |
| 276 |
change to take effect. |
| 277 |
|
| 278 |
!!! success "Verification" |
| 279 |
After enabling, verify that permissions still work correctly: |
| 280 |
|
| 281 |
```python |
| 282 |
from guardian.shortcuts import get_perms |
| 283 |
from myapp.models import Project |
| 284 |
|
| 285 |
project = Project.objects.first() |
| 286 |
print(get_perms(user, project)) |
| 287 |
``` |
| 288 |
|
| 289 |
The output should match the permissions that were previously assigned |
| 290 |
via the generic tables. |
| 291 |
|
| 292 |
At this point you can disable maintenance mode and resume normal operations: |
| 293 |
|
| 294 |
```bash |
| 295 |
python manage.py maintenance_mode off |
| 296 |
``` |
| 297 |
|
| 298 |
--- |
| 299 |
|
| 300 |
## Step 4 — Clean Up Generic Records |
| 301 |
|
| 302 |
After the migration is verified and the direct tables are actively in use, the |
| 303 |
old generic records for the migrated models are **no longer read** by |
| 304 |
django-guardian. However, they still occupy space in the database. Leaving them |
| 305 |
in place has two negative consequences: |
| 306 |
|
| 307 |
1. **Database bloat.** The `guardian_userobjectpermission` and |
| 308 |
`guardian_groupobjectpermission` tables retain rows that are never queried, |
| 309 |
wasting storage and slowing down maintenance operations like `VACUUM` or |
| 310 |
index rebuilds. |
| 311 |
|
| 312 |
2. **Stale data risk.** If the `enabled = False` flag is accidentally |
| 313 |
reintroduced (e.g. during a merge conflict), django-guardian will fall back |
| 314 |
to reading the generic tables. Those records are now **stale** — they do |
| 315 |
not reflect permission changes made after the migration — and will produce |
| 316 |
incorrect authorization decisions that are extremely hard to debug. |
| 317 |
|
| 318 |
!!! danger "Important" |
| 319 |
It is **strongly recommended** to delete the orphaned generic records once |
| 320 |
you are confident the direct foreign key setup is working correctly. |
| 321 |
|
| 322 |
Create a dedicated cleanup migration: |
| 323 |
|
| 324 |
```python |
| 325 |
# myapp/migrations/XXXX_cleanup_generic_perms.py |
| 326 |
|
| 327 |
from django.db import migrations |
| 328 |
|
| 329 |
|
| 330 |
def cleanup_generic_records(apps, schema_editor): |
| 331 |
ContentType = apps.get_model("contenttypes", "ContentType") |
| 332 |
UserObjectPermission = apps.get_model("guardian", "UserObjectPermission") |
| 333 |
GroupObjectPermission = apps.get_model("guardian", "GroupObjectPermission") |
| 334 |
|
| 335 |
Project = apps.get_model("myapp", "Project") |
| 336 |
project_ct = ContentType.objects.get_for_model(Project) |
| 337 |
|
| 338 |
UserObjectPermission.objects.filter(content_type=project_ct).delete() |
| 339 |
GroupObjectPermission.objects.filter(content_type=project_ct).delete() |
| 340 |
|
| 341 |
|
| 342 |
class Migration(migrations.Migration): |
| 343 |
|
| 344 |
dependencies = [ |
| 345 |
("myapp", "XXXX_migrate_to_direct_fk"), # replace with actual name |
| 346 |
("guardian", "0001_initial"), |
| 347 |
("contenttypes", "0002_remove_content_type_name"), |
| 348 |
] |
| 349 |
|
| 350 |
operations = [ |
| 351 |
migrations.RunPython(cleanup_generic_records, migrations.RunPython.noop), |
| 352 |
] |
| 353 |
``` |
| 354 |
|
| 355 |
!!! tip |
| 356 |
If you are not comfortable with an irreversible cleanup, keep a |
| 357 |
database backup taken **after Step 2** as your rollback safety net. |
| 358 |
|
| 359 |
--- |
| 360 |
|
| 361 |
## Quick Reference |
| 362 |
|
| 363 |
| Step | Action | Downtime Required | |
| 364 |
|---|---|---| |
| 365 |
| **Prep** | Backup database, enable maintenance mode | Yes | |
| 366 |
| **1** | Define direct FK models with `enabled = False`, run `makemigrations` + `migrate` | No (schema only) | |
| 367 |
| **2** | Data migration — copy generic → direct with `bulk_create` | Yes | |
| 368 |
| **3** | Remove `enabled = False`, deploy | No (app restart) | |
| 369 |
| **4** | Delete stale generic records | No | |
| 370 |
| **Post** | Disable maintenance mode, verify | — | |