-1

I have a Query:

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)

And I want to get all articles by specific category. I try to make such a request:

query {
  categoryArticles(category: "SPORT") {
    title
  }
}

But it returns me:

{
  "data": {
    "categoryArticles": null
  }
}

Does somebody know what I do wrong or how to get articles by specific category? I will be very grateful if somebody can help. Thanks!

Exoriri
  • 327
  • 3
  • 21

4 Answers4

1

There is a naming convention for the resolving functions of the query class, you prepend resolve_ to the class variable.

If Article.objects.get(category = category) returns desired result, it should work.

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 rename it to category_article since it is returning one article, then you also have to rename the function to resolve_category_article

0

Change your getAllArticlesByCategory to return an Article QuerySet.

It could look somewhat similar to this.

def resolve_articles_by_category(self, info, **kwargs):
    return Article.objects.filter(category__name=kwargs.get('category_name'))
0

So, the easiest way to do it is to use this https://docs.graphene-python.org/projects/django/en/latest/filtering/.

In my case it will look like this:

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)
Exoriri
  • 327
  • 3
  • 21
0

Was long time ago, but what helped is as @xadm mentioned documantation link in the comments.

docs.graphene-python.org/projects/django/en/latest/filtering

Exoriri
  • 327
  • 3
  • 21