Django 按月/按季度对 DateField() 数据进行分组

发布于 2024-09-26 15:22:36 字数 532 浏览 0 评论 0原文

我有一个 django 模型,其中包含一个 DateField() 属性:

class Table():
    date = models.DateField()
    value = models.FloatField()

我正在编写一个视图,按周、月、季度和年份对这些数据进行分组。 我已经硬编码了一个计算,通过将当月的所有值相加并除以有多少条目,可以简单地获得我的每月值 - 但我觉得必须有一种更优雅的方法来做到这一点。

我的目标是这样的:

get_monthly(Table.objects.all())
>>> [123, 412, 123, 534, 234, 423, 312, 412, 123, 534, 234, 423]
get_quarterly(Table.objects.all())
>>> [123, 412, 123, 534]

列表中的值是每个月的平均值。

谁能帮助我吗?

I've got a django model which contains, among other things, a DateField() attribute:

class Table():
    date = models.DateField()
    value = models.FloatField()

I'm writing a view that groups this data by week, month Quarter and year.
I've hardcoded a calculation that gets my monthly value simply enough - by adding up all the values in that month and deviding by how many entries there were - but I feel like there must be a more elegant way of doing this.

What I'm aiming for is something like this:

get_monthly(Table.objects.all())
>>> [123, 412, 123, 534, 234, 423, 312, 412, 123, 534, 234, 423]
get_quarterly(Table.objects.all())
>>> [123, 412, 123, 534]

Where the values in the list are averages of each month.

Can anyone help me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叹沉浮 2024-10-03 15:22:36

您可以使用模型的查询功能来完成此操作。
以下是每月查询的示例:

from django.db.models import Avg
Table.objects.extra(select={'month':"strftime('%m',date)"}).values('month').annotate(Avg('value'))

您可能希望将 strftime('%m',date) 更改为 month(date) 或任何其他计算,具体取决于您的情况数据库日期时间功能。

You can do this using the model's query capabilities.
Here's an example for the monthly query:

from django.db.models import Avg
Table.objects.extra(select={'month':"strftime('%m',date)"}).values('month').annotate(Avg('value'))

Where you may want to change strftime('%m',date) with month(date) or any other calculation, depending on your database datetime functionality.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文