【问题标题】:Get pub_date value using filters使用过滤器获取 pub_date 值
【发布时间】:2013-05-25 10:14:56
【问题描述】:

我需要一些帮助来学习如何使用过滤器获取“日期时间”值。

我正在获取一个按年份显示销售订单的表格。

如何改进我的代码以获取它?

models.py

 class Ventas(models.Model):
      codigoventa = models.CharField(max_length=7, unique=True)
      codigocliente = models.ForeignKey('Clientes')
      Fecha_registro = models.DateTimeField("Fecha de edicion", auto_now_add=True) 
      totalventa = models.DecimalField(max_digits=10, decimal_places = 2)
      codigosucursal = models.ForeignKey('Sucursales')
      totalventa = models.IntegerField()

      def __unicode__(self):
          return self.codigoventa
      class Meta:
            ordering = ['-pub_date']

views.py

def ventas_anio(request):
    ventas = Ventas.objects.filter(Fecha_registro=datetime(2013, 1, 30))
    return render_to_response('ventasanual.html',{'datos':ventas}, context_instance=RequestContext(request))

【问题讨论】:

    标签: python django django-queryset


    【解决方案1】:

    如果你想按特定日期过滤,要么

    import datetime
    the_day = datetime.date(2013, 1, 30)
    Ventas.objects.filter(Fecha_registro__gte=the_day, 
                          Fecha_registro__lt=the_day+datetime.timedelta(1))
    

    或者

    Ventas.objects.extra(where=["DATE(Fecha_registro)=%s"], params=['2013-01-30'])
    

    或低效但可行

    Ventas.objects.filter(Fecha_registro__year=2013, 
                          Fecha_registro__month=1,
                          Fecha_registro__day=30)
    

    gteltextrayearmonthday的文档是here

    【讨论】:

    • 感谢它的工作原理,但......我可以按月排序吗?例如按月显示销售额。
    • @dcft 这可能很棘手。检查 stackoverflow.com/questions/4236226/… ,将 MONTH 替换为 EXTRACT('month' FROM ...) 或其他取决于您的数据库后端的类型..
    • 我已经这样做了,但我还有一个问题...请看My question stackoverflow.com/questions/16827380/… 对我来说使用过滤器非常有趣,我今晚学到了很多东西
    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多