Graphene/Django (GraphQL): How to use a query argument in order to exclude nodes matching a specific filter?
我在
在React应用程序中,我想通过GraphQL一方面查询当前用户拥有的所有视频,另一方面查询当前用户不拥有的所有视频。
我可以在客户端运行以下
1 2 3 4 5 6 7 8 9 10 11 12 13 | query AllScenes { allScenes { edges { node { id, name, owner { name } } } } } |
我希望有两个带有过滤器参数的查询,直接向我的后端询问相关数据。类似于:
1 2 3 4 5 6 7 8 9 10 11 12 13 | query AllScenes($ownerName : String!, $exclude: Boolean!) { allScenes(owner__name: $ownerName, exclude: $exclude) { edges { node { id, name, owner { name } } } } } |
我会用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | from project.scene_manager.models import Scenea۬ from graphene import ObjectType, relay, Int, String, Field, Boolean, Floata۬ from graphene.contrib.django.filter import DjangoFilterConnectionField from graphene.contrib.django.types import DjangoNodea۬ from django_filters import FilterSet, CharFilter a۬a۬a۬ class SceneNode(DjangoNode): a۬ class Meta:a۬ model = Scene a۬a۬a۬class SceneFilter(FilterSet):a۬ owner__name = CharFilter(lookup_type='exact', exclude=exclude) a۬ class Meta:a۬ model = Scenea۬ fields = ['owner__name']a۬a۬ class Query(ObjectType):a۬a۬ scene = relay.NodeField(SceneNode)a۬ all_scenes = DjangoFilterConnectionField(SceneNode, filterset_class=SceneFilter, exclude=Boolean())a۬a۬ def resolve_exclude(self, args, info):a۬ exclude = args.get('exclude')a۬ return excludea۬a۬a۬ class Meta:a۬ abstract = True |
使用了我的自定义
切换到graphene-django 1.0,我已经可以使用以下查询定义执行所需的操作:
1 2 3 4 5 6 7 8 9 10 11 12 | 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上提出了另一种解决方案