按Year_Month排序Django过滤器 [英] Sorting by Year_Month Django filter

查看:238
本文介绍了按Year_Month排序Django过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以视图中的年份,月份显示信息顺序,如何改进我的代码获取?

I try to show information order by year, month in a view, How can I improve my code for getting it?

提示:我正在工作报告显示销售订单按年和月,帮助我

Hint: I'm working in a report which shows sales ordering by year and month, Help me

谢谢。

views.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))


推荐答案

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

You can use a dict of month names instead of individual month name variables. (Your locale must be set correctly for month_name to be in your language)

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

然后,您可以将 dict 作为上下文返回。或者,如果您不想更改模板端的任何内容。

You can then simply return the dict as context. Or, if you don't wish to change anything in the template side.

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

这篇关于按Year_Month排序Django过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆