【问题标题】:Sorting by Year_Month Django filter按 Year_Month 排序 Django 过滤器
【发布时间】:2013-05-30 03:17:08
【问题描述】:

我尝试在视图中按年、月显示信息顺序,如何改进获取它的代码?

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

谢谢。

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

【问题讨论】:

  • 您可以创建使用查询集注释来实现您正在寻找的内容
  • ventas是没有is_validQuerySet,可能你的意思是if ventas.exists()或者直接评价if ventas:

标签: python django django-models


【解决方案1】:

您可以使用月份名称的dict 来代替单独的月份名称变量。 (您的语言环境必须正确设置,month_name 才能使用您的语言)

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

【讨论】:

    猜你喜欢
    • 2021-09-13
    • 2011-01-31
    • 2017-01-23
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多