Get query to return list of values instead of objects in graphene-django
Asked Answered
D

1

6

My django model looks as follows:

class Article(model.Model):
    slug = models.SlugField(db_index=True, max_length=255, unique=True)
    title = models.CharField(db_index=True, max_length=255)
    body = models.TextField()

    tags = models.ManyToManyField(
        'articles.Tag', related_name='articles'
    )

    def __str__(self):
        return self.title

class Tag(model.Model):
    tag = models.CharField(max_length=255)
    slug = models.SlugField(db_index=True, unique=True)

    def __str__(self):
        return self.tag

And my schema.py:

class ArticleType(DjangoObjectType):
    class Meta:
        model = Article

class Query(ObjectType):
    article = graphene.Field(ArticleType, slug=graphene.String())

    def resolve_article(self, info, slug):
        article = Article.objects.get(slug=slug)
        return article

Querying this model with:

query {
  article(slug: "my_slug") {
    id
    title
    body
    slug
    tagList: tags {
      tag
    }
  }
}

Produces:

{
  "data": {
    "article": {
      "id": "1",
      "title": "How to train your dragon 1",
      "slug": "how-to-train-your-dragon-y41h1x",
      "tagList": [
        {
          "tag": "dragon",
          "tag": "flies"
        }
      ]
    }
  }
}

**Question: ** How can I customize the returned json output? In particular, tagList is a list of objects where the "tag" key is redundant. I would instead like to return a list of strings such that the output becomes:

{
  "data": {
    "article": {
      "id": "1",
      "title": "How to train your dragon 1",
      "slug": "how-to-train-your-dragon-y41h1x",
      "tagList": ["dragon","flies"]
    }
  }
}

How can I do this??

Dominicadominical answered 9/8, 2018 at 8:58 Comment(0)
B
13

Add a custom tag_list field to your ArticleType with a resolver that returns a list of strings. Something like:

class ArticleType(DjangoObjectType):
    tag_list = graphene.List(graphene.String)

    class Meta:
         model = Article

    def resolve_tag_list(self, info):
         return [tag.tag for tag in self.tags.all()]
Bagasse answered 9/8, 2018 at 16:5 Comment(1)
Thanks Mark! Been struggling with this the entire day... You answer also helped improve my understanding of graphene-django! For others reference the final query became: query { article(slug: "my_slug") { id title body slug tagList } }Dominicadominical

© 2022 - 2024 — McMap. All rights reserved.