gpt4 book ai didi

python - graphene-django - 如何过滤?

转载 作者:太空狗 更新时间:2023-10-29 18:27:20 24 4
gpt4 key购买 nike

我使用 graphen-django 构建 GraphQL API。我已成功创建此 API,但无法传递参数来过滤我的响应。

这是我的 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

这是我的schema.py: 进口 Graphite 烯 从 graphene_django 导入 DjangoObjectType 从模型导入应用程序

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)

我的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)),
]

如您所见,我还有一个 REST API。

我的 settings.py 包含这个:

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

我遵循这个:https://github.com/graphql-python/graphene-django

当我发送这个请求时:

{
applications {
name
}
}

我得到了这样的回复:

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

所以,成功了!

但是当我尝试传递这样的参数时:

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

我有这样的回应:

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

我错过了什么?还是我做错了什么?

最佳答案

我找到了解决方案,感谢:https://docs.graphene-python.org/projects/django/en/latest/

这是我的答案。我已经编辑了我的 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)

然后,它缺少一个包:django-filter ( https://github.com/carltongibson/django-filter/tree/master )。Django-filter 由 DjangoFilterConnectionField 使用。

现在我可以这样做了:

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

响应将是:

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

关于python - graphene-django - 如何过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com