根据Django按日期计算记录数 [英] Count number of records by date in Django

查看:1405
本文介绍了根据Django按日期计算记录数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下的模型:

  class Review(models.Model):
places = models.ForeignKey(Venue,db_index = True)
review = models.TextField()
datetime_created = models.DateTimeField(default = datetime.now)
pre>

我想查询数据库以获取按天分组的场地的总评价数。 MySQL查询将是:

  SELECT DATE(datetime_created),count(id)
FROM REVIEW
WHERE places_id = 2
GROUP BY DATE(datetime_created);

Django中最好的方法是什么?我可以使用

  Review.objects.filter(places__pk = 2)
/ pre>

并在视图中解析结果,但对我来说似乎不合适。

解决方案

这应该可以使用(使用与您使用的相同的MySQL特定功能):

  object.filter(places_pk = 2)
.extra({'date_created':date(datetime_created)})
.values('date_created')
.annotate(created_count = Count 'id'))


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)

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

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.

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆