回复应该包含帖子的细节和该帖子的点赞数量。我的模型看起来像这样:
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、content和count of liked_by。
发布于 2021-06-28 16:30:27
这就是我解决这个问题的方法。
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 = CountableConnectionBasefrom 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
}
}
}
}https://stackoverflow.com/questions/68069214
复制相似问题