1👍
Yes, it will work. Check out https://docs.python.org/3/library/stdtypes.html#truth-value-testing. As long as user
is not empty it will return True
.
By default, an object is considered true unless its class defines
either a bool() method that returns False or a len() method
that returns zero, when called with the object.
So even though the object user
is NOT a Boolean
, it will be treated as such when doing any logical comparisons.
In fact this is a way one often checks to see if a queryset is empty:
if some_queryset:
print("There is at least one object in some_queryset")
Although, as the docs say, the exists() method is a bit faster, and better, if you don’t need the actual queryset, and just want to know if the queryset is empty or not.
EDIT
To answer your question you posted in the comment, you must separate each condition you are testing in the if .. or
: In other words, if you want to test if A equals B or C or D, the you cannot do:
if A == B or C or D
Instead you must do,
if A == B or A == C or A == D
Thus your code should look like this:
class ExamplePermission(BasePermission):
def has_permission(self, request, view):
user = CustomUser.objects.filter(user=request.user).first()
if view.action == 'list':
return user
elif request.method == 'POST' or request.method == 'PATCH' or view.action == 'destroy' or view.action == 'update':
return user and user.user_type == ADMIN
else:
return False