django - 获取查询以返回值列表而不是 graphene-django 中的对象
问题描述
我的 django 模型如下所示:
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
还有我的 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
使用以下命令查询此模型:
query {
article(slug: "my_slug") {
id
title
body
slug
tagList: tags {
tag
}
}
}
产生:
{
"data": {
"article": {
"id": "1",
"title": "How to train your dragon 1",
"slug": "how-to-train-your-dragon-y41h1x",
"tagList": [
{
"tag": "dragon",
"tag": "flies"
}
]
}
}
}
**问题:** 如何自定义返回的 json 输出?特别是,tagList 是一个对象列表,其中“tag”键是多余的。相反,我想返回一个字符串列表,使输出变为:
{
"data": {
"article": {
"id": "1",
"title": "How to train your dragon 1",
"slug": "how-to-train-your-dragon-y41h1x",
"tagList": ["dragon","flies"]
}
}
}
我怎样才能做到这一点??
解决方案
ArticleType
使用返回字符串列表的解析器向您添加自定义 tag_list 字段。就像是:
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()]
推荐阅读
- .net - 更新列表类型的视图模型属性
来自 HTML.TextBoxFor - javascript - 如何将几个数组运算符合并为一个?Javascript
- artificial-intelligence - pacman 启发式函数的问题
- java - 为什么 /logout 调用会抛出“方法不允许”?
- sql - Spark sql对窗口函数的不同计数
- python - 通过条件pyspark相互减去列内的多个值
- c# - 持有一对相同类型的值
- javascript - 如何在内部超时的情况下获得地图中的所有承诺
- c# - 我应该如何在 ASP.NET Core 中为具有多个 URI 端点的资源实现 REST API 控制器?
- c# - 在 C# PSObject 中,当 PS 命令行确实返回值时,PSPropertyInfo 不返回值