Graphene / Django(GraphQL):如何在不访问某些字段的情况下执行查询?

时间:2018-07-10 11:55:58

标签: python django graphql graphene-python

我的计划很简单。模型是来自Django的自定义用户。

class UserFilter(django_filters.FilterSet):
    class Meta:
        model = User
        fields = ['username', 'email', ]

class UserNode(DjangoObjectType):
    class Meta:
        model = User
        only_fields = (
            'username',
            'email',
            'is_staff',
            'is_active',
            'is_superuser',
            'last_login',
            'date_joined',
            'profile',
        )
        interfaces = (graphene.relay.Node, )

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

        if user:
            return user
        return None

class Query(graphene.ObjectType):
   users = DjangoFilterConnectionField(
        UserNode,
        filterset_class=UserFilter,
    )
def resolve_users(self, info):
        user = info.context.user
        if user.is_anonymous:
            raise Exception('You aren't autorized')
        elif not user.is_superuser:
            return get_user_model().objects.defer("email")
        elif user.is_superuser:
            return get_user_model().objects.all().select_related('profile')
        else:
            raise Exception('Error')

当我向不是超级用户的用户发出请求时,在架构中我指定了“电子邮件”字段,答案给出了该字段的值。

query{
    users{
        edges{
            node{
                id
                username
                email
                isSuperuser
            }
        }
    }
}

我得到:

{
    "data": {
        "users": {
            "edges": [
{
                    "node": {
                        "id": "VXNlck5vZGU6NQ==",
                        "username": "Test4",
                        "email": "Test4@test.ru",
                        "isSuperuser": false
                    }
                }
            ]
        }
    }
}

是否有可能区分对resolve_users中字段的访问?过滤器中的异常不起作用。也许我没有正确理解DjangoFilterConnectionField的设计,我应该使用通常的列表将其输出到GraphQL。

0 个答案:

没有答案