【问题标题】:Django Query set for counting records each month用于每月统计记录的 Django 查询集
【发布时间】:2018-09-16 12:25:08
【问题描述】:
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')

上面查询集的结果是这样的:

<QuerySet [(1, 31), (2, 27), (3, 31), (4, 30), (5, 31), (6, 29), (7, 30), (8, 31), (9, 30), (10, 31), (11, 30),
 (12, 31)]>

我希望查询集能够自动从数据库中获取月度范围,而无需将年份放入查询集

我要显示的数据是这样的:

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


enter code here

【问题讨论】:

    标签: python django django-queryset


    【解决方案1】:

    使用TruncMonthdb函数从日期字段中提取月份

    做这样的事情,

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


    这个 ORM 将生成一个 SQL 查询,

    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}]>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多