按年份/月份Django fi排序

2024-04-26 04:12:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在视图中,我尝试按年、月显示信息顺序,如何改进代码以获取信息?你知道吗

提示:我正在写一份按年度和月份显示销售订单的报告,请帮助我

谢谢。你知道吗

你知道吗视图.py你知道吗

 def ventas_mes_anio(request):
     ventas = Ventas.objects.filter(Fecha_registro__range=["2011-01-01", "2013-12-31"])
     if ventas.is_valid():
         enero = Ventas.objects.filter(Fecha_registro__month=1)
         febrero = Ventas.objects.filter(Fecha_registro__month=2)
         marzo = Ventas.objects.filter(Fecha_registro__month=3)
         abril = Ventas.objects.filter(Fecha_registro__month=4)
         mayo = Ventas.objects.filter(Fecha_registro__month=5)
         junio = Ventas.objects.filter(Fecha_registro__month=6)
         julio = Ventas.objects.filter(Fecha_registro__month=7)
         agosto = Ventas.objects.filter(Fecha_registro__month=8)
         septiembre = Ventas.objects.filter(Fecha_registro__month=9)
         octubre = Ventas.objects.filter(Fecha_registro__month=10)
         noviembre = Ventas.objects.filter(Fecha_registro__month=11)
         diciembre = Ventas.objects.filter(Fecha_registro__month=12)

    return render_to_response('ventasxproductosxmes.html',{'datos':ventas,'enero':enero,'febrero':febrero,'marzo':marzo,'abril':abril,'mayo':mayo,'junio':junio,'julio':julio,'agosto':agosto,'septiembre':septiembre,'octubre':octubre,'noviembre':noviembre,'diciembre':diciembre,},context_instance=RequestContext(request))

Tags: objectsfilterregistromonthmayoagostofechaventas
1条回答
网友
1楼 · 发布于 2024-04-26 04:12:16

您可以使用月份名称的dict,而不是单个月份名称变量。(必须正确设置区域设置,才能使月份名称使用您的语言)

    import calendar
    months = dict(zip(calendar.month_name[1:], [Ventas.objects.filter(Fecha_registro__month=x) for x in xrange(1,13)]))

然后只需将dict作为上下文返回即可。或者,如果您不想更改模板方面的任何内容。你知道吗

ret = {'datos':ventas}
ret.update(months)
return render_to_response('ventasxproductosxmes.html',ret,context_instance=RequestContext(request))

相关问题 更多 >