在Django中按日期计算记录数 [英] Count number of records by date in Django
本文介绍了在Django中按日期计算记录数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似于以下的模型:
I have a model similar to the following:
class Review(models.Model):
venue = models.ForeignKey(Venue, db_index=True)
review = models.TextField()
datetime_created = models.DateTimeField(default=datetime.now)
我想查询数据库以获取按天分组的场所的评论总数.MySQL 查询将是:
I'd like to query the database to get the total number of reviews for a venue grouped by day. The MySQL query would be:
SELECT DATE(datetime_created), count(id)
FROM REVIEW
WHERE venue_id = 2
GROUP BY DATE(datetime_created);
在 Django 中完成此任务的最佳方法是什么?我可以用
What is the best way to accomplish this in Django? I could just use
Review.objects.filter(venue__pk=2)
并在视图中解析结果,但这对我来说似乎不对.
and parse the results in the view, but that doesn't seem right to me.
推荐答案
这应该可以工作(使用您使用的相同 MySQL 特定功能):
This should work (using the same MySQL specific function you used):
Review.objects.filter(venue__pk=2)
.extra({'date_created' : "date(datetime_created)"})
.values('date_created')
.annotate(created_count=Count('id'))
这篇关于在Django中按日期计算记录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文