【问题标题】:How do I get the number of posts on each day with annotation in Django?如何在 Django 中获取每天带有注释的帖子数?
【发布时间】:2012-04-26 18:24:04
【问题描述】:

我有一个Post 模型,其中有一个datetime.date 字段用于posted_date。我需要找出用户每天发了多少帖子。为每一天创建一个查询似乎很愚蠢。

我不知道如何使用 annotate 进行聚合 API 查询。

Post.objects.filter(author=someuser).annotate(dailycount=Count('posted_day'))

正确的方法?那么,我如何使用它来获取特定日期的帖子数?

我的模型是:

class Post(models.Model):
    posted_day=models.DateField(default=date.today)
    author=models.ForeignKey(User,null=True)

【问题讨论】:

    标签: python django django-queryset annotate


    【解决方案1】:

    你快到了。您需要两个附加子句:

    day_counts = Post.objects.filter(author=someuser).values('posted_day').annotate(
                                           dailycount=Count('posted_day')).order_by()
    

    values('posted_day') 启用分组,空的order_by 确保结果按posted_day 排序,因此默认排序不会干扰。

    这方面最清晰的文档似乎在Order of annotate() and values() clausesDjango Aggregation docs 部分。

    values 返回 listdicts 喜欢:

    [{'posted-day': 'the-first-day', 'dailycount': 2}, . . . ,
     {'posted-day': 'the-last-day', 'dailycount': 3}]
    

    因此,如果您想要用户发布的最后一天,它将是列表中的最后一项:

    last_day_dict = day_counts[-1]
    date = last_day_dict['posted_day']
    count = last_day_dict['dailycount']
    

    然后,您可以比较 datetoday() 以查看它们是否匹配,如果不匹配,则用户今天没有发帖,如果他发帖,则他发布了 count 次。

    【讨论】:

    • 感谢您的回复..从返回的查询集中,我如何找到day1 上的帖子数量,即datetime.date.today()
    • @damon 我在答案中添加了更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2012-03-10
    相关资源
    最近更新 更多