lundi 18 février 2019

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 would you go about writing this? Thank you very much 😊

Aucun commentaire:

Enregistrer un commentaire