如果我有一个定义Widget的Django模型:
class Widget(models.Model):
type = models.CharField()
sold = models.DateTimeField()
price = models.DecimalField()
.
.
我如何获得特定年份每月销售的小部件的总价值?
我想最终列出12个月总计,例如:
[1225, 197, 131, 125, ...
这表明1月份售出的小工具总价值为1225美元,2月份为197美元等。
我希望这可以通过Django查询完成,但不太确定如何。
更新
我不希望使用任何特定于数据库的内容来简化更改数据库。我不介意它是不是都在一个查询中完成。进行查询,然后使用Python进行一些操作就可以了。
更新
我想我可以稍微改变一些代码来回答我提出的另一个问题:
queryset = Widget.objects.filter(sold__year=year)
totals = [0] * 12
for widget in queryset:
totals[widget.sold.month - 1] += widget.price
return totals
如果我错过了某些内容或者有更好的方法,请告诉我。
答案 0 :(得分:0)
基于你可以做的this answer。
Widget.objects.extra(select={'year': "EXTRACT(year FROM sold)", 'month': "EXTRACT(month from sold)"}).values('year', 'month').annotate(Sum('price'))
会给你类似的东西
[{'price__sum': 1111, 'year': 2010L, 'month': 6L}...]
编辑 - 不使用EXTRACT
可能效率不高但是......
for date in Widget.objects.all().dates('sold','month'):
values["%s_%s" % (date.year,date.month)] = Widget.objects.filter(sold__month=date.month,sold__year=date.year).aggregate(Sum('price'))
答案 1 :(得分:0)
类似的方法,但可能效率不高
month_totals = []
for month in range(1, 13):
month_total = Widget.objects. \
filter(sold__gte=datetime.date(the_year, month, 1),
sold__lte=datetime.date(the_year, month, 31)). \
aggregate(month_total=Sum('price')).month_total
month_totals.append(month_total)