most_viewed_videos = Video.objects.filter(
videowatch__created__month=today.month,
viewing__status="D"
).annotate(
count=Count("videowatch"),
viewing_count=Sum("viewing")
).values("count", "viewing_count").order_by(
"-viewing_count",
"-count"
)
嘿,我有这段代码片段,我的问题是如何将 count
和 viewing_count
加在一起得到一个结果。
我尝试过,但没有发现任何有效的方法。
编辑: 解决方案对我有用
most_viewed_videos = Video.objects.filter( videowatch__created__month=today.month, viewing__status="D" ).extra( select={'total': 'COUNT("videowatch") + SUM(CAST("viewing" as CHAR))'} ).values("total").order_by("-total")
最佳答案
简单地你可以在不使用.extra()的情况下实现它,这是解决方案:
most_viewed_videos = Video.objects.filter(
videowatch__created__month=today.month,
viewing__status="D"
).annotate(
count=Count("videowatch"),
viewing_count=Sum("viewing"),
count_viewing_count = Sum(F(Count("videowatch"))+F(Count("viewing")))
).values("count", "viewing_count").order_by(
"-viewing_count",
"-count"
)
我没有测试过,但它应该可以工作
关于python - 一起计算注释字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18083728/