微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 graphene-django 查询将回复作为喜欢帖子的成员数量发送

如何解决使用 graphene-django 查询将回复作为喜欢帖子的成员数量发送

回复应包含帖子的详细信息和该帖子的点赞数。我的模型看起来像:

class Post():
    created_by = models.ForeignKey(User,related_name="creator_post",on_delete=models.PROTECT)  
    group = models.ForeignKey(Group,related_name= "group_post",on_delete=models.PROTECT,null=True,blank=True)
    content = models.TextField(default="",blank=True)
    liked_by = models.ManyToManyField(User,blank=True)
    shared_post = models.ManyToManyField('self',blank=True)
    comment_log = models.ForeignKey(CommentLog,related_name = "comment_log_post",blank=True,on_delete=models.PROTECT)

响应应该包含 created_by、内容和喜欢的数量

解决方法

我就是这样解决的。

import graphene
from graphene import relay
class CountableConnectionBase(relay.Connection):
    class Meta:
        abstract = True

    total_count = graphene.Int()
    def resolve_total_count(self,info,**kwargs):
        return self.iterable.count()

graphene.relay.Connection = CountableConnectionBase

class PostType(DjangoObjectType):
    class Meta:
        model = Post
        filter_fields = ['content','created_by',"liked_by","group"]
        interfaces = (relay.Node,)
        connection_class = CountableConnectionBase

from graphene_django.filter import DjangoFilterConnectionField
class Query(object):
    posts = DjangoFilterConnectionField(PostType)
    @permissions_checker([IsAuthenticated])
    def resolve_posts(self,**kwargs):
        try:
            authenticated_user = info.context.user
            return Post.objects.filter(created_by = authenticated_user.rider.id)
        except:
            raise Exception("No Posts available.")

查询:


{
  posts (content:"Post updated",first:2){
   totalCount
  edges {
     node {
       content,likedBy{
           totalCount
         
       }
     }
      cursor
   }
    pageInfo {
       endCursor
       hasNextPage
     }
 }
}

输出:

{
    "data": {
        "posts": {
            "totalCount": 1,"edges": [
                {
                    "node": {
                        "content": "Post updatedd","likedBy": {
                            "totalCount": 0
                        }
                    },"cursor": "YXJyYXljb25uZWN0aW9uOjA="
                }
            ],"pageInfo": {
                "endCursor": "YXJyYXljb25uZWN0aW9uOjA=","hasNextPage": false
            }
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。