【问题标题】:Get query to return list of values instead of objects in graphene-django获取查询以返回值列表而不是 graphene-django 中的对象
【发布时间】:2019-01-16 16:06:15
【问题描述】:

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

我该怎么做??

【问题讨论】:

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


    【解决方案1】:

    使用返回字符串列表的解析器将自定义 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的理解!对于其他人参考,最终查询变为: query { article(slug: "my_slug") { id title body slug tagList } }
    猜你喜欢
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2021-09-18
    • 2021-02-28
    • 2021-09-20
    相关资源
    最近更新 更多