-1

I have a permission class for my viewset. But it has multiple if statements and the if statements can be added others as well if some action added inside viewset.

So how can I optimize my code here for better performance ?

 def has_permission(self, request, view):
     user = request.user
     if view.action in ["update", "partial_update"]:
         return user.is_manager
     if view.action == "create":
         return user.is_creator
     if view.action in ["list", "retrieve"]:
         return user.is_viewer
     if view.action == "destroy":
         return user.is_admin
     return False

Here different type of view actions would be performed by different user types.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
D_P
  • 802
  • 10
  • 32

2 Answers2

1

Your method is actually fine, but if you are looking for a slightly more concise way, try this:

def has_permission(self, request, view):
    user = request.user
    actions = {"update": user.is_manager,
               "partial_update": user.is_manager,
               "create": user.is_creator,
               "list": user.is_viewer,
               "retrieve": user.is_viewer,
               "destroy": user.is_admin}
    return actions.get(view.action, False)
Selcuk
  • 57,004
  • 12
  • 102
  • 110
-1

If your code is working well and you just want to optimize code than may be this could help you:

def has_permission(self, request, view):
        if view.action in ["update", "partial_update","list", "retrieve","destroy","create"]:
            return some_user
        return False
sunil ghimire
  • 505
  • 4
  • 14