[英]graphene-django - How to filter?
我使用 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 :從 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"
}
}
]
}
}
}
如果您在我的情況下不想使用 Relay,您也可以使用 Django orm 過濾直接在解析器中處理過濾。 此處示例:在 django 中過濾 graphql 查詢
對 Adrien Answer 的補充很少。 如果您想在過濾時執行不同的操作,例如包含和精確匹配,請編輯您的schema.py
class ApplicationNode(DjangoObjectType):
class Meta:
model = Application
# Provide more complex lookup types
filter_fields = {
'name': ['exact', 'icontains', 'istartswith']
}
interfaces = (relay.Node, )
你可以像這樣編寫查詢
query {
allApplications(name_Icontains: "test") {
edges {
node {
id,
name
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.