Django 更新每个用户的monthly_score,其中包含他们所有帖子的总喜欢数



我想为每个用户的Profile更新monthly_score字段。

我有一个Post模型,其中包含一种返回帖子喜欢的方法,称为like_count.

如何使用:

Profile.objects.update(monthly_score=Subquery()) 

获取用户本月的帖子并返回他们所有喜欢的总和?

我试过这个,但没有用:

Profile.objects.update(
monthly_score = Subquery(
Post.objects.filter(
user = Profile.user,
date_posted__month = today.month
).aggregate(Sum(like_count))
)
)

列表推导呢? 像这样:

[Profile.objects.filter(pk = profile_item.pk).update(
monthly_score = sum(
[post_item.like_count() for post_item in Post.objects.filter(
user = profile_item.user, 
date_posted__month = today.month
)]
)
) for profile_item in Profile.objects.all()]

PS:修复了@AlphaDjango在评论中写的错误。

相关内容

最新更新