简体   繁体   中英

A custom argument in graphene-django

How do I create a custom argument in GraphQL with graphene-django?

I currently have this configuration in my 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)

But I have not been able to figure out how to make "username" a required argument in the actual GraphQL query on "post".

Not sure if this was supported before but i am using graphene-django>=2.15,<2.16 and i can confirm the following syntax works as expected:

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 also deals with it properly: 带参数的GraphiQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM