2

I am using Django + GraphQL and it is extremely convenient to use DjangoListField. It allows me to override get_queryset at the ObjectType level and make sure all permissions verified there. In that manner I have a single place to have all my permission checks.

However, whenever I need to do something like:

contract = graphene.Field(ClientContractType,
                              pk=graphene.ID(required=True))

I have to also duplicate permissions validation in the resolve_contract method. I came up with the following solution to ensure permission and avoid duplication:

    def resolve_contract(self, info, pk):
        qs = ClientContract.objects.filter(pk=pk)
        return ClientContractType.get_queryset(qs, info).get()

It works but I'd love to have some sort of DjangoObjectField which will encapsulate this for me and, potentially, pass arguments to the ClientContractType in some way. Have someone had this problem or knows a better solution?

Andrii Zarubin
  • 2,165
  • 1
  • 18
  • 31

1 Answers1

0

The best I was able to come up with is to move this logic into the ObjectType class, defining a method (analogues to what DjangoObjectType already implemented)

    @classmethod
    def get_node(cls, info, id):
        queryset = cls.get_queryset(cls._meta.model.objects, info)
        try:
            return queryset.get(pk=id)
        except cls._meta.model.DoesNotExist:
            return None

then, resolver will look like


    def resolve_contract(self, info, pk):
        return ClientContractType.get_node(pk)

Far from ideal, tho.

Andrii Zarubin
  • 2,165
  • 1
  • 18
  • 31