所以我试图用某个类别的帖子填充新闻提要。然后我希望能够显示帖子上的回复数量。我对如何做到这一点感到困惑的原因是,因为我按类别过滤了目标,然后过滤了与所有这些目标相关的所有帖子,现在我有一个包含帖子主体、目标描述和创建日期的字典列表,但我还想添加回复的数量,我不确定如何以一种有效的方式做到这一点。此外,我意识到我在view.py中做事情的方式不太理想,所以任何建议都会很棒!
Model.py
class Post(AbstractBaseModel):
creator_id = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post_creator_id")
goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE)
body = models.CharField(max_length=511, validators=[MinLengthValidator(5)])
hash_tags = models.ManyToManyField(HashTag)
class ReplyPost(AbstractBaseModel):
creator_id = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="reply")
post_id = models.ForeignKey(Post, on_delete=models.CASCADE)
body = models.CharField(max_length=250)
View.py
@api_view(['GET'])
def get_most_recent_posts_by_category(request, category, count):
goals_list = list(Goal.objects.filter(category = category).values_list('uuid', flat=True))
data = list(Post.objects.filter(goal_id__in=goals_list).order_by('created').values('body', 'goal_id__description', 'created'))
data['goal_description'] = data['goal_id__description']
data['post_body'] = data['body']
del data['goal_description']
del data['body']
return JsonResponse(data, status=status.HTTP_200_OK)
您可以使用Count('replypost')
来添加项目的数量:
from django.db.models import Count
data = list(
Post.objects.filter(
goal_id__in=goals_list
).order_by(
'created'
).values(
'body', 'goal_id__description', 'created', replies=Count('replypost')
)
)