简体   繁体   English

如何通过DateTimeField()使用Django ORM对Postgresql数据库中的项目进行计数

[英]How to count items in Postgresql-database with Django ORM by DateTimeField()

We have a Django application with a Postgresql database. 我们有一个带有Postgresql数据库的Django应用程序。 We have a model that contains a DateTimeField() . 我们有一个包含DateTimeField()的模型。

How do we count the items by hour per day? 我们如何每天按小时计数项目? So that we get something like: 这样我们就可以得到:

July 2, 2016, 4 p.m. | 10
July 2, 2016, 5 p.m. | 12
...
July 3, 2016, 4 p.m. | 7
July 3, 2016, 5 p.m. | 11

# myapp/models.py

class MyModel(models.Model):
    my_date = models.DateTimeField()

# myapp/views.py

def object_count():
    query = MyModel.objects.how_to_count_items_by_hour_per_day

Django 1.10 introduces new database functions ( Extract and Trunc ): Django 1.10引入了新的数据库功能( ExtractTrunc ):

from django.db.models import DateTimeField, Count
from django.db.models.functions import Trunc

MyModel.objects.annotate(
    day_hour=Trunc('my_date', 'hour', output_field=DateTimeField())
).values('day_hour').annotate(items=Count('id'))

尝试:

MyModel.objects.values('my_date__date', 'my_date__hour').annotate(Count('id'))

So, until Django 1.10, this looks to be about the best way: 因此,在Django 1.10之前,这似乎是最好的方法:

jobs = MyModel.objects.filter(my_date__lte=datetime.now()).extra({"hour": "date_trunc('hour', my_date)"}).values(
        "hour").order_by('my_date').annotate(count=Count("id"))

The above code is modified from that which is given from the blog that is linked below to group by hour from the DateTimeField() 上面的代码是从博客中给出的代码修改而来的,该博客在下面链接到DateTimeField()按小时分组

Django Aggregation: group by day Django汇总:按天分组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM