Search code examples
pythongraphene-pythongraphene-django

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


The response should contain the details of post and number of likes for that post. My model looks like:

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)

The response should have created_by, content and count of liked_by.


Solution

  • This is how I resolved it.

    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.")
    

    Query:

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

    Output:

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