我有一张表格如下:
+-------+---------+---------------------+-------------+-----------+-----------------+
| id | user_id | visit_time | action | user_type | erp_customer_id |
+-------+---------+---------------------+-------------+-----------+-----------------+
| 17460 | 818 | 2017-05-15 15:02:13 | NULL | customer | 932 |
| 17459 | 818 | 2017-05-15 15:02:11 | NULL | customer | 932 |
| 17458 | 818 | 2017-05-15 15:01:56 | NULL | customer | 932 |
| 17457 | 818 | 2017-05-15 15:01:55 | NULL | customer | 932 |
| 17456 | 818 | 2017-05-15 15:01:47 | NULL | customer | 932 |
| 17455 | 818 | 2017-05-15 15:01:15 | NULL | customer | 932 |
| 17454 | 818 | 2017-05-15 15:00:44 | NULL | customer | 932 |
| 17453 | 818 | 2017-05-15 14:59:58 | NULL | customer | 932 |
| 17452 | 818 | 2017-05-15 14:59:55 | NULL | customer | 932 |
| 17451 | 818 | 2017-05-15 14:59:55 | NULL | customer | 932 |
| 17450 | 818 | 2017-05-15 14:59:52 | NULL | customer | 932 |
| 17449 | 817 | 2017-05-15 14:55:46 | NULL | customer | 931 |
| 17448 | 817 | 2017-05-15 14:55:45 | NULL | customer | 931 |
| 17447 | 817 | 2017-05-15 14:53:55 | NULL | customer | 931 |
| 17446 | 817 | 2017-05-15 14:53:54 | NULL | customer | 931 |
| 17445 | 817 | 2017-05-15 14:53:26 | NULL | customer | 931 |
user_id
是外键,visit_time
是访问页面的时间戳。
我们的想法是找出每个用户一天的访问次数。每个用户每天都应该返回一个单独的行。
所以看起来应该是这样的:
{'user' : 818 , 'day' : 2017-05-15 , 'visits' : 12}
{'user' : 817 , 'day' : 2017-05-15 , 'visits' : 5 }
我正在尝试使用Django ORM构建查询。
这是模型定义:
class Log(models.Model):
class Meta:
db_table = "users_log"
managed = False
user = models.ForeignKey(LoginCustomer , db_column = "user_id")
customer = models.ForeignKey(Customer , db_column = "erp_customer_id")
visit_time = models.DateTimeField()
user_type = models.CharField(max_length = 25)
我已经能够使用以下内容从visit_time
中提取日期
Log.objects.annotate(day = RawSQL('DATE(visit_time)',[]))
如何使用Django ORM获得所需数据?
正在使用的数据库是MySQL。
答案 0 :(得分:2)
您需要使用
from django.db.models import Count
from django.db.models.functions import TruncDay
Log.objects
.annotate(period=TruncDay('visit_time'))
.values('period', 'user_id')
.annotate(visits=Count('id'))
.values('period', 'visits')