Можно ли объединить несколько вызовов API exists() queryset в один вызов БД с помощью annotate?

У меня есть функция decorator.py для проверки, имеет ли зарегистрированный пользователь разрешение на доступ к представлению.

def allow_only_admins_authors_coauthors_reviewers_specialists(view_func):
    def wrapper_func(request, *args, **kwargs):

        email_of_logged_user = request.user.email
        book_id = kwargs['pk'] # Get the book id

        if (request.user.is_admin or \
        
        (Coauthors.objects.filter(paper=book_id, email=request.user).exists()) or \

        (Book.objects.filter(Q(id=book_id, author=request.user) | Q(id=book_id, author__email__in=request.user.get_secondary_emails_flat_list)).exists()) or \

        (Token.objects.filter(   
            
                                Q(book=book_id, email=email_of_logged_user) |
                                Q(book=book_id, email_which_was_actually_used_to_retrive_token__emails__icontains = email_of_logged_user)

                                # 'email_which_was_actually_used_to_retrive_token' contains the actual email which was used by the reviewer to retrieve the token. Its different than the email to which the token was originally sent.
        
                                ).exists()
        # Sometimes, the token might be deleted. In such case, system shall check if the logged user is the reviewer within the Review model.
        ) or \
        
        (Review.objects.filter(paper=book_id, user__email = email_of_logged_user).exists()) or \

        (SpecialistAssignment.objects.filter(raw_book=book_id, user=request.user).exists())):
            return view_func(request, *args, **kwargs)
        else:
            return HttpResponse('You are not authorised to view this page!')
    return wrapper_func

Эта функция сделает несколько обращений к БД из-за многочисленных проверок API exists().

Есть ли способ объединить эти несколько exists() в один запрос к БД с помощью annotate?

Во-вторых, быстрее ли этот подход, чем использование django-rules?

Вернуться на верх