我想为每个用户的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在评论中写的错误。