使用 graphene-django 查询将响应作为喜欢 post 的成员计数发送

Send the response as count of members who have liked a post using graphene-django query

响应应包含 post 的详细信息和 post 的点赞数。我的模型看起来像:

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,null=True, on_delete=models.PROTECT)

响应应具有 created_by、liked_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, info, **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
            }
        }
    }
}