| 1 |
--- |
| 2 |
title: Performance |
| 3 |
description: Performance implications and optimizations when using django-guardian. |
| 4 |
--- |
| 5 |
|
| 6 |
# Performance Tuning |
| 7 |
|
| 8 |
It is important to remember that by default `django-guardian` uses |
| 9 |
generic foreign keys to retain relation with any Django model. For most |
| 10 |
cases, it's probably good enough, however if we have a lot of queries |
| 11 |
being spanned and our database seems to be choking it might be a good |
| 12 |
choice to use *direct* foreign keys. Let's start with quick overview of |
| 13 |
how generic solution work and then we will move on to the tuning part. |
| 14 |
|
| 15 |
## Default, generic solution |
| 16 |
|
| 17 |
`django-guardian` comes with two models: |
| 18 |
`UserObjectPermission` and `GroupObjectPermission`. They both have |
| 19 |
same, generic way of pointing to other models: |
| 20 |
|
| 21 |
- `content_type` field telling what table (model class) target |
| 22 |
permission references to (`ContentType` instance) |
| 23 |
- `object_pk` field storing value of target model instance primary key |
| 24 |
- `content_object` field being a `GenericForeignKey`. Actually, it is |
| 25 |
not a foreign key in standard, relational database meaning - it is |
| 26 |
simply a proxy that can retrieve proper model instance being |
| 27 |
targeted by two previous fields |
| 28 |
|
| 29 |
!!! tip "See Also" |
| 30 |
[Django generic relations](https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#generic-relations) |
| 31 |
|
| 32 |
Let's consider following model: |
| 33 |
|
| 34 |
``` python |
| 35 |
class Project(models.Model): |
| 36 |
name = models.CharField(max_length=128, unique=True) |
| 37 |
``` |
| 38 |
|
| 39 |
To add a *change_project* permission for *joe* user we would |
| 40 |
use `api-shortcuts-assign` shortcut: |
| 41 |
|
| 42 |
``` python |
| 43 |
>>> from guardian.shortcuts import assign_perm |
| 44 |
>>> project = Project.objects.get(name='Foobar') |
| 45 |
>>> joe = User.objects.get(username='joe') |
| 46 |
>>> assign_perm('change_project', joe, project) |
| 47 |
``` |
| 48 |
|
| 49 |
What it really does is: create an instance of |
| 50 |
`UserObjectPermission`. Something |
| 51 |
similar to: |
| 52 |
|
| 53 |
``` python |
| 54 |
>>> content_type = ContentType.objects.get_for_model(Project) |
| 55 |
>>> perm = Permission.objects.get(content_type__app_label='app', |
| 56 |
... codename='change_project') |
| 57 |
>>> UserObjectPermission.objects.create(user=joe, content_type=content_type, |
| 58 |
... permission=perm, object_pk=project.pk) |
| 59 |
``` |
| 60 |
|
| 61 |
As there are no real foreign keys pointing at the target model, this |
| 62 |
solution might not be enough for all cases. For example, if we try to |
| 63 |
build an issues tracking service and we'd like to be able to support |
| 64 |
thousands of users and their project/tickets, object level permission |
| 65 |
checks can be slow with this generic solution. |
| 66 |
|
| 67 |
## Direct foreign keys |
| 68 |
|
| 69 |
!!! abstract "Added in version 1.1" |
| 70 |
|
| 71 |
To make our permission checks faster, we can use a direct foreign key. |
| 72 |
It is straightforward to set up; |
| 73 |
All we need to do is to declare two new models next to our `Project` model, |
| 74 |
one for `User` and one for `Group` models: |
| 75 |
|
| 76 |
``` python |
| 77 |
from guardian.models import UserObjectPermissionBase |
| 78 |
from guardian.models import GroupObjectPermissionBase |
| 79 |
|
| 80 |
class Project(models.Model): |
| 81 |
name = models.CharField(max_length=128, unique=True) |
| 82 |
|
| 83 |
class ProjectUserObjectPermission(UserObjectPermissionBase): |
| 84 |
content_object = models.ForeignKey( |
| 85 |
Project, on_delete=models.CASCADE, related_name='user_object_permissions' |
| 86 |
) |
| 87 |
|
| 88 |
class ProjectGroupObjectPermission(GroupObjectPermissionBase): |
| 89 |
content_object = models.ForeignKey( |
| 90 |
Project, on_delete=models.CASCADE, related_name='group_object_permissions' |
| 91 |
) |
| 92 |
``` |
| 93 |
|
| 94 |
!!! danger "Important" |
| 95 |
Name of the `ForeignKey` field is important and it should be |
| 96 |
`content_object` as underlying queries depends on it. |
| 97 |
|
| 98 |
!!! warning "Reverse accessor clashes" |
| 99 |
If `content_object` points to the same model as the inherited `user` |
| 100 |
or `group` foreign key (e.g., you are assigning permissions on a custom |
| 101 |
User model), Django will raise a reverse accessor clash error. To fix |
| 102 |
this, set a unique `related_name` on the `content_object` field as |
| 103 |
shown in the example above. |
| 104 |
|
| 105 |
From now on, `guardian` will figure out that `Project` model has direct |
| 106 |
relation for user/group object permissions and will use those models. It |
| 107 |
is also possible to use only user or only group-based direct relation, |
| 108 |
however it is discouraged (it's not consistent and might be a quick |
| 109 |
road to hell from the maintenance point of view, especially). |
| 110 |
|
| 111 |
To temporarily disable the detection of this direct relation model, add |
| 112 |
`enabled = False` to the object permission model classes. This is useful |
| 113 |
to allow the ORM to create the tables for you and for you to migrate |
| 114 |
data from the generic model tables before using the direct models. |
| 115 |
|
| 116 |
!!! note |
| 117 |
By defining direct relation models we can also tweak that object |
| 118 |
permission model, i.e. by adding some fields. |
| 119 |
|
| 120 |
## Prefetching permissions |
| 121 |
|
| 122 |
!!! abstract "Added in version 1.4.3" |
| 123 |
|
| 124 |
Naively looping through objects and checking permissions on each one |
| 125 |
using `has_perms` results in a permissions lookup in the database for |
| 126 |
each object. Large numbers of objects therefore produce large numbers of |
| 127 |
database queries which can considerably slow down your app. To avoid |
| 128 |
this, create an `ObjectPermissionChecker` and use its `prefetch_perms` |
| 129 |
method before looping through the objects. This will do a single lookup |
| 130 |
for all the objects and cache the results. |
| 131 |
|
| 132 |
``` python |
| 133 |
from guardian.core import ObjectPermissionChecker |
| 134 |
|
| 135 |
joe = User.objects.get(username='joe') |
| 136 |
projects = Project.objects.all() |
| 137 |
checker = ObjectPermissionChecker(joe) |
| 138 |
|
| 139 |
# Prefetch the permissions |
| 140 |
checker.prefetch_perms(projects) |
| 141 |
|
| 142 |
for project in projects: |
| 143 |
# No additional lookups needed to check permissions |
| 144 |
checker.has_perm('change_project', project) |
| 145 |
``` |