3

I have some video items in a Django/Graphene backend setup. Each video item is linked to one owner. In a React app, I would like to query via GraphQL all the videos owned by the current user on the one hand and all the videos NOT owned by the current user on the other hand.

I could run the following GraphQl query and filter on the client side:

query AllScenes {
  allScenes {
    edges {
      node {
        id,
        name,
        owner {
          name
        }
      }
    }
  }
}

I would rather have two queries with filters parameters directly asking relevant data to my backend. Something like:

query AllScenes($ownerName : String!, $exclude: Boolean!) {
  allScenes(owner__name: $ownerName, exclude: $exclude) {
    edges {
      node {
        id,
        name,
        owner {
          name
        }
      }
    }
  }
}

I would query with ownerName = currentUserName and exclude = True/False yet I just cannot retrieve my exclude argument on my backend side. Here is the code I have tried in my schema.py file:

from project.scene_manager.models import Scene

from graphene import ObjectType, relay, Int, String, Field, Boolean, Float

from graphene.contrib.django.filter import DjangoFilterConnectionField
from graphene.contrib.django.types import DjangoNode

from django_filters import FilterSet, CharFilter





class SceneNode(DjangoNode):

    class Meta:

        model = Scene





class SceneFilter(FilterSet):

    owner__name = CharFilter(lookup_type='exact', exclude=exclude)


    class Meta:

        model = Scene

        fields = ['owner__name']


    
class Query(ObjectType):


    scene = relay.NodeField(SceneNode)

    all_scenes = DjangoFilterConnectionField(SceneNode, filterset_class=SceneFilter, exclude=Boolean())



    def resolve_exclude(self, args, info):

        exclude = args.get('exclude')

        return exclude




    class Meta:

        abstract = True

My custom SceneFilter is used but I do not know how to pass the exclude arg to it. (I do not think that I am making a proper use of the resolver). Any help on that matter would be much appreciated!

4

1 回答 1

3

切换到graphene-django 1.0,我已经能够使用以下查询定义做我想做的事:

class Query(AbstractType):

    selected_scenes = DjangoFilterConnectionField(SceneNode, exclude=Boolean())

    def resolve_selected_scenes(self, args, context, info):
        owner__name = args.get('owner__name')
        exclude = args.get('exclude')
        if exclude:
            selected_scenes = Scene.objects.exclude(owner__name=owner__name)
        else:
            selected_scenes = Scene.objects.filter(owner__name=owner__name)
        return selected_scenes

BossGrand在 GitHub 上提出了另一个解决方案

于 2016-09-29T15:30:37.660 回答