pythondjangoif-statementdjango-rest-frameworkpython-object

How to check if an object is within an array's objects values?


I'm building a server for Django Rest Framework. It models houses, contracts and owners. Basically, a House can have several Contracts and each Contract has an Owner.

I'm writing a custom permission for a DetailViews for the Houses which should only allow the request, if you own the House (if you have a Contract for that House and you are the Owner.

Here is what I have so far:

class UserOwnsTheHouseSlugInUrlPermission(permissions.BasePermission):
    """
    Permission to check if the user is an owner for the given House.
    This permission needs a house_slug to be given in the url.
    """
    message = _(USER_IS_NOT_OWNER_PERMISSION_DENIED_MESSAGE)

    def has_object_permission(self, request, view, obj):
        owner = get_object_or_None(UserOwnerProfile, user=request.user)
        if owner and owner in obj.contracts.owner:
            return True

        return False

This code does not work. In JavaScript you could write:

if(obj.contracts.map(contract => contract.owner).includes(owner))

Or something similar. Python is not my main language, so I don't know how to express that condition in Python or Django.

How can I go about writing this?


Solution

  • As I mentioned in the comment, the issue is not one of Python syntax. The problem is that obj.contracts is presumably a ForeignKey, which returns a queryset; a queryset wouldn't have an owner attribute, that is a field on each of the model instances within the queryset.

    Now you could do this to get a list of all the owners:

    if owner and owner in obj.contracts.values_list('owner', flat=True)
    

    but that would be the wrong solution. What you actually want to do is to ask the database if the owner is in the list of contract owners:

    if owner and obj.contracts.filter(owner=owner).exists()