Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 每月盘点记录的Django查询集_Python_Django_Django Queryset - Fatal编程技术网

Python 每月盘点记录的Django查询集

Python 每月盘点记录的Django查询集,python,django,django-queryset,Python,Django,Django Queryset,我想在模型中显示每个月的总记录。我找到的解决方案要求我进入第二年 class Orders(models.Model): orderid = models.IntegerField(db_column='orderID', primary_key=True) pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True) 上述查询集的结果如下所示: Orders.objects.filter

我想在模型中显示每个月的总记录。我找到的解决方案要求我进入第二年

class Orders(models.Model):
  orderid = models.IntegerField(db_column='orderID', primary_key=True) 
  pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True)  
上述查询集的结果如下所示:

Orders.objects.filter(pickupdate__year = '2006').values_list('pickupdate__month').annotate(total = Count('orderid')
使用db函数从日期字段中提取月份

这样做,

Month        | Total 
January 2007 | 1
February 2007| 2
etc


enter code here

此ORM将生成SQL查询,如下所示:

from django.db.models import Count
from django.db.models.functions import TruncMonth

Orders.objects.annotate(month=TruncMonth('pickupdate')).values('month').annotate(total=Count('orderid'))


示例

SELECT django_date_trunc('month', "sample_orders"."pickupDate") AS "month", COUNT("sample_orders"."orderID") AS "total" FROM "sample_orders" GROUP BY django_date_trunc('month', "sample_orders"."pickupDate")
[8]中的
:来自django.db.models导入计数
在[9]中:从django.db.models.functions导入TruncMonth
[10]中的Orders.objects.annotate(month=truncmount('pickupdate')).values('month').annotate(total=Count('orderid'))
出[10]:
SELECT django_date_trunc('month', "sample_orders"."pickupDate") AS "month", COUNT("sample_orders"."orderID") AS "total" FROM "sample_orders" GROUP BY django_date_trunc('month', "sample_orders"."pickupDate")
In [8]: from django.db.models import Count

In [9]: from django.db.models.functions import TruncMonth

In [10]: Orders.objects.annotate(month=TruncMonth('pickupdate')).values('month').annotate(total=Count('orderid'))
Out[10]: <QuerySet [{'month': datetime.date(2018, 8, 1), 'total': 2}, {'month': datetime.date(2018, 9, 1), 'total': 4}]>