How to get OR permissions instead of AND in REST framework

Now DRF allows permissions to be composed using bitwise operators: & -and- and | -or-.

From the docs:

Provided they inherit from rest_framework.permissions.BasePermission, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written:

from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ReadOnly(BasePermission):
    def has_permission(self, request, view):
        return request.method in SAFE_METHODS

class ExampleView(APIView):
    permission_classes = (IsAuthenticated|ReadOnly,)

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

Edited: Please note there is a comma after IsAuthenticated|ReadOnly.


I think you might be able to use django-rules library here. Link

It is a rule based engine very similar to decision trees and it can be easily integrated with permissions_class framework of DRF.

The best part is you can perform set operations on simple permissions and create complex permissions from them.

Example

>>> @rules.predicate
>>> def is_admin(user):
...     return user.is_staff 
...


>>> @rules.predicate
>>> def is_object_owner(user, object):
        return object.owner == user

Predicates can do pretty much anything with the given arguments, but must always return True if the condition they check is true, False otherwise. Now combining these two predicates..

is_object_editable = is_object_owner | is_admin

You can use this new predicate rule is_object_editable inside your has_permissions method of permission class.