Graphene-django - How to filter?

I am using graphen-django to build the GraphQL API. I successfully create this API, but I cannot pass an argument to filter my response.

This is my models.py :

from django.db import models class Application(models.Model): name = models.CharField("nom", unique=True, max_length=255) sonarQube_URL = models.CharField("Url SonarQube", max_length=255, blank=True, null=True) def __unicode__(self): return self.name 

This is my schema.py : graphene import from graphene_django import DjangoObjectType from import Application models

 class Applications(DjangoObjectType): class Meta: model = Application class Query(graphene.ObjectType): applications = graphene.List(Applications) @graphene.resolve_only_args def resolve_applications(self): return Application.objects.all() schema = graphene.Schema(query=Query) 

My urls.py :

 urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', authviews.obtain_auth_token), url(r'^graphql', GraphQLView.as_view(graphiql=True)), ] 

As you can see, I also have a REST API.

My settings.py contains the following:

 GRAPHENE = { 'SCHEMA': 'tibco.schema.schema' } 

I follow this: https://github.com/graphql-python/graphene-django

When sending this request:

 { applications { name } } 

I have an answer:

 { "data": { "applications": [ { "name": "foo" }, { "name": "bar" } ] } } 

So it works!

But when I try to pass such an argument:

 { applications(name: "foo") { name id } } 

I have this answer:

 { "errors": [ { "message": "Unknown argument \"name\" on field \"applications\" of type \"Query\".", "locations": [ { "column": 16, "line": 2 } ] } ] } 

What did I miss? Or maybe I'm something wrong?

+10
source share
1 answer

I found a solution thanks to: https://docs.graphene-python.org/projects/django/en/latest/

This is my answer. I changed my schema.py :

 import graphene from graphene import relay, AbstractType, ObjectType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from models import Application class ApplicationNode(DjangoObjectType): class Meta: model = Application filter_fields = ['name', 'sonarQube_URL'] interfaces = (relay.Node, ) class Query(ObjectType): application = relay.Node.Field(ApplicationNode) all_applications = DjangoFilterConnectionField(ApplicationNode) schema = graphene.Schema(query=Query) 

Then the package was missing: django-filter ( https://github.com/carltongibson/django-filter/tree/master ). The django filter is used by the DjangoFilterConnectionField.

Now I can do this:

 query { allApplications(name: "Foo") { edges { node { name } } } } 

and the answer will be:

 { "data": { "allApplications": { "edges": [ { "node": { "name": "Foo" } } ] } } } 
+12
source

Source: https://habr.com/ru/post/1011947/


All Articles