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??
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()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With