我有一个查询:
class Query(object):
all_articles = graphene.List(ArticleType)
category_articles = graphene.List(ArticleType, category = graphene.String())
def resolve_all_articles(self, info, **kwargs):
return Article.objects.all()
def resolve_article_by_category(self, info, **kwargs):
category = kwargs.get('category')
return Article.objects.get(category = category)
我想按特定类别获取所有文章。我尝试提出这样的要求:
query {
categoryArticles(category: "SPORT") {
title
}
}
但它返回我:
{
"data": {
"categoryArticles": null
}
}
有人知道我做错了什么,或者如何按特定类别获取文章?如果有人可以帮助我,我将非常感激。谢谢!
答案 0 :(得分:1)
查询类的解析函数有一个命名约定, 您将 resolve _ 放在类变量的前面。
如果Article.objects.get(category = category)
返回期望的结果,它应该可以工作。
category_articles = graphene.List(ArticleType, category = graphene.String())
def resolve_category_articles(self, info, **kwargs):
category = kwargs.get('category')
return Article.objects.get(category = category)
N.B将其重命名为category_article
,因为它返回了一篇文章,那么您还必须将函数重命名为resolve_category_article
答案 1 :(得分:0)
更改您的getAllArticlesByCategory以返回商品查询集。
看起来可能与此类似。
Root
Category 1
Sub 1
Product 1
Product 2
Sub 2
Product 3
Product 4
答案 2 :(得分:0)
因此,最简单的方法是使用此https://docs.graphene-python.org/projects/django/en/latest/filtering/。
在我的情况下,它将如下所示:
import graphene
from graphene_django.types import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from .models import Article, User
class ArticleNode(DjangoObjectType):
class Meta:
model = Article
filter_fields = ['category']
interfaces = (graphene.relay.Node,)
class Query(object):
all_articles = DjangoFilterConnectionField(ArticleNode)