Performance: Object-level permissions concept
This concept affects server response time and client perceived latency by controlling access checks at a fine-grained level.
Jump into concepts and practice - no test required
permitted_ids = get_permitted_object_ids(user, objects) for obj in objects: if obj.id in permitted_ids: display(obj)
for obj in objects: if not user.has_perm('view_obj', obj): continue display(obj)
| Pattern | Database Queries | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Per-object permission check in loop | N permission queries | 0 | 0 | [X] Bad |
| Batch permission check before loop | 1 permission query | 0 | 0 | [OK] Good |
has_perm method to accept an object as a second argument for object-level checks.has_perm with object, which is correct. user.has_perm('app.view_model') lacks object, so it's model-level. Options C and D use incorrect method names.from guardian.shortcuts import assign_perm
assign_perm('change_article', user, article)
if user.has_perm('change_article', article):
print('Can edit')
else:
print('Cannot edit')assign_perm function assigns the 'change_article' permission to the user for the specific article object.user.has_perm('change_article', article) call returns True because the permission was assigned.if user.has_perm('delete_post'):
print('Can delete')
else:
print('Cannot delete')has_perm must include the object as the second argument.has_perm without the object, so it checks model-level permission only, not object-level.