如何在石墨烯中将函数作为查询结果返回?

问题描述

我有一个帖子模型,我想知道当前登录的用户是否喜欢该帖子:

是否可以进行此项工作,还是应该使用其他请求来了解用户是否喜欢该帖子:

class PostNode(DjangoObjectType):
    id = graphene.ID(source='pk',required=True)
    liked = graphene.Boolean(source=Like.objects.filter(user=info.context.user,post=Post.objects.get(pk=id)))
    class Meta:
        model = Post
        interfaces = (graphene.relay.Node,)

(当然不起作用)

查询:

query {
posts {
  edges {
    node {
      liked
      title
      text
    }
  }
}

}

结果:

{
   "data": {
       "posts": {
           "edges": [
               {
                   "node": {
                       "liked": false,"title": "hi","text": "m"
                   }
               },{
                   "node": {
                      "liked": true,"title": "blalblala","text": "blalalblala"
                    }
               }
           ]
       }
   }
}

解决方法

您可以使用 custom resolvers 来实现此行为,如下所示:

class PostNode(DjangoObjectType):
    id = graphene.ID(required=True)
    liked = graphene.Boolean()

    class Meta:
        model = Post
        interfaces = (graphene.relay.Node,)

    def resolve_liked(parent,info):
        # "parent" here is the Post model instance
        return Like.objects.exists(user=info.context.user,post=parent)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...