[Django]-Django ORM access optimization with Filter

0๐Ÿ‘

โœ…

As mentioned by Klaus, this is a database killer. If there lots of permissions (even without any apps of your own, there will be quite a few), you could potentially find yourself executing hundreds of queries in your user_has_perm function. You could reduce that with caching

from django.core.cache import cache.

def user_has_perm(user, *permissions_to_check):
    hash = # create a hash from user.id and permissions_to_check.
           # maybe something as simple as "".join(permissions_to_check)

    perms = cache.get(hash)
    if perms: 
         return perms

    permission_check = True
    permissions_not_found = []

    user_groups = user.groups.all().prefetch_related('permissions')

    for permission in permissions_to_check:
        content_type, permission_codename = permission.split('.')
        if not user.has_perm(permission) and not user_groups.filter(
                permissions__content_type__model__icontains=content_type,
                permissions__codename__icontains=permission_codename).exists():  # Goes down from Groups to the single user permission
            permission_check = False
            permissions_not_found.append(permission)

    cache.set(hash, [permisson_check, permissions_not_found], 10**5)
    return permission_check, permissions_not_found
๐Ÿ‘คe4c5

Leave a comment