【问题标题】:A custom argument in graphene-djangographene-django 中的自定义参数
【发布时间】:2019-04-26 11:07:30
【问题描述】:

如何使用 graphene-django 在 GraphQL 中创建自定义参数?

我目前在我的 schema.py 中有这个配置:

class Post(DjangoObjectType):
    class Meta:
        model = FeedPost
        interfaces = (graphene.relay.Node,)
        filter_fields = ['id']

class Query(graphene.ObjectType):
         post = graphene.Node.Field(Post)

    def resolve_post(self, info, **kwargs):
        username = kwargs.get('username')
        u = User.objects.get(username=username) 
        users_sources = FeedSource.objects.filter(user=u)
        return FeedPost.objects.filter(feed__feedsource__in=users_sources).annotate(
             source_title=F('feed__feedsource__title')
    )
schema = graphene.Schema(query=Query)

但我无法弄清楚如何在“post”的实际 GraphQL 查询中将“用户名”作为必需参数。

【问题讨论】:

  • 您可以选择添加username 作为Post 输入类型的一部分,或者作为查询的另一个单独参数。由于您没有显示您的 Post 模型,因此尚不清楚用户名是否已经是其中的一部分。

标签: django graphql graphene-python


【解决方案1】:

不确定之前是否支持此功能,但我使用的是 graphene-django>=2.15,,我可以确认以下语法按预期工作:

class Query(graphene.ObjectType):

    # Notice the username argument
    post = graphene.Field(Post, username=graphene.String(required=True, default=None))

    def resolve_post(self, root, info, username): # Notice: the username argument spelled exactly as before
        u = User.objects.get(username=username) 
        users_sources = FeedSource.objects.filter(user=u)
        return FeedPost.objects.filter(feed__feedsource__in=users_sources).annotate(
             source_title=F('feed__feedsource__title')
    )

GraphiQL 也能正确处理它:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-19
    • 2021-11-26
    • 2018-05-17
    • 2022-12-31
    • 2019-02-06
    • 2018-08-27
    • 1970-01-01
    • 2021-01-22
    相关资源
    最近更新 更多