Django- Group by 和 Count by unique 在一起

标签 django django-queryset django-orm django-aggregation

我有以下模型:

class Post(models.Model):
    title = models.CharField(max_length=30)

class PostView(models.Model):
    post = models.ForeignKey(Post, related_name='views', on_delete=models.CASCADE)
    user = models.ForeignKey(get_user_model(), related_name='my_views')
    created = models.DateTimeField(auto_now_add=True)

我想获得帖子的浏览量,按一天中的小时分组并且是唯一的。
例如,如果用户在上午 10 点看到一个帖子 20 次,则应只计算一次。 我在几个小时内按 View (不是唯一 View )获得帖子,如下所示:

from django.db.models.functions import TruncHour
from django.db.models import Count

qs = PostView.objects.all().annotate(
        hour=TruncHour('created')
    ).values(
        'hour'
    ).annotate(
        c=Count('id')
    ).values('hour', 'c')

以上代码会将所有观看次数计算为总观看次数。我想通过 user_idhour 以及 post_id 一起获得独特的观点。 可以用 ORM 做到这一点吗?

最佳答案

你可以这样做,

from django.db.models import Count

result = PostView.objects.values(
    <b>"created__hour",
    "post",
    "user"</b>
).annotate(count=Count("id"))

print(list(result))

# Result
# [{'created__hour': 17, 'post': 1, 'user': 1, 'count': 4}, {'created__hour': 17, 'post': 2, 'user': 1, 'count': 3}]

关于Django- Group by 和 Count by unique 在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67483681/

相关文章:

django - Apache 挂起 mod_wsgi + django

django - 无法通过域 URL 访问 Nginx 站点

python - Django - 使用从类似 REST 的 API 检索的数据构建报告的应用程序

django - 每次运行 django 代码时如何创建新的 postgreSQL 行以保存数据

python - 自动合并任意 Django 模型

django - 使用 Django ORM 值并调用成员函数

python - Mongodb:检查数组字段是否包含数字或字符串

python - Django如何基于ManyToManyField进行过滤?

python - 如何在 Django 中按日期范围过滤查询对象?

python - 在模板中使用 Django 查询集会影响数据库吗?