django - 获取查询以返回值列表,而不是graphene-django中的对象

标签 django django-rest-framework graphql graphene-python

我的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"]
    }
  }
}

我怎样才能做到这一点??

最佳答案

使用可返回字符串列表的解析器,将自定义tag_list字段添加到ArticleType中。就像是:

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()]

关于django - 获取查询以返回值列表,而不是graphene-django中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51762817/

相关文章:

javascript - Ajax 搜索功能在 django 应用程序中不起作用

django - TDD Django 测试似乎跳过了 View 代码的某些部分

python - Django Rest-framework 不会在调用之间存储经过身份验证的用户

graphql - Apollo GraphQL 中的命令式是什么意思?

django - Django 中 STATICFILES_DIRS 的路径

python - Django错误: cannot import name autodiscover_modules

Django Rest Framework 返回空 JSON

python - 类型对象 'User' 没有属性 'objects' (AbstractUser) python

python - 卖家电商 : How to batch insert products through python code or API

express - Apollo Server Express : Request entity too large