Skip to main content
 首页 » 编程设计

python之一起计算注释字段

2025年05月04日7kenshinobiy

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" 
        ) 

我没有测试过,但它应该可以工作