Skip to main content
 首页 » 编程设计

python之如何在 Django 中对日期和时间执行聚合

2025年01月19日37傻小

假设我有以下简单模型,用于演示目的:

class Something(models.Model): 
    date = models.DateField()   
    time = models.TimeField()   
    timestamp = models.DateTimeField()  
    price = models.DecimalField() 
    manufacturer = models.CharField() 

如果我想获得每个制造商的总数,我可以执行如下操作:

Something.objects.all().values("manufacturer").annotate(frequency=Count(field)) 

我的目标是根据日期和时间做类似的事情。例如每个月的总计数。

由于已经有基于上述模型的数据,我的第一个想法是添加自定义属性,但您不能将其与values 一起使用。

接下来,我想将必要的字段(日、月、年...)添加到模型中,并添加一个自定义的save 方法来计算它们。

另一种方法是将查询集加载到 pandas 中并在那里进行计算。

有没有更合适的方法来做这样的事情?

请您参考如下方法:

你可以这样使用:

from django.db.models.functions import TruncMonth 
 
Something.objects 
      .annotate(month=TruncMonth('timestamp')) # Truncate to month to select 
      .values('month') # Group By month 
      .annotate(frequency=Count(field))  # Get count