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

嘿,我有这个代码片段,我的问题是如何将countand 加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")
4

2 回答 2

1

您可以使用.extra queryset 方法来实现:

most_viewed_videos = Video.objects.filter(
        videowatch__created__month=today.month,
        viewing__status="D"
    ).annotate(
        count=Count("videowatch"),
        viewing_count=Sum("viewing")
    .extra(
        select={'total': 'COUNT(videowatch)+SUM(viewing)'}
    )
    ).values("count", "viewing_count").order_by(
        "-viewing_count",
        "-count"
)

我还没有测试过。我遇到了类似的问题“对先前注释值的注释”。似乎不可能,我过去曾开过一张票,但它已关闭。

于 2013-08-06T15:14:03.780 回答
1

只需您无需使用 .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"
        )

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

于 2022-01-03T09:06:37.043 回答