本文介绍了处理日期请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要通过request.GET发送两个日期值,用于过滤querySet:

  

在客户端,ref 生成格式为'YYYY-mm-dd'的日期字符串。


I am sending two date values over request.GET for filtering a querySet:

if 'from_date' in request.GET:
            from_date = request.GET['from_date']
            if 'to_date' in request.GET:
                to_date = request.GET['to_date']
            else:
                to_date = datetime.date.today()
            calls_queryset = calls_queryset.filter(contact_date__range=(from_date, to_date))

The filter__range breaks though. It seems it doesn't like the date format I am sending over.

?from_date=08/08/2012&to_date=08/29/2012

I think I have to cast them to be a date before placing them in range, is this correct? What is the most efficient way to do this?

Many Thanks

解决方案

The DateField supports converting from 'YYYY-mm-dd' formats to python datetime.date:

>>> from django.db import models
>>> models.DateField().to_python('2012-08-22')
datetime.date(2012, 8, 22)

Hence the range lookup accepts strings as parameters:

>>> from django.contrib.auth.models import User
>>> print User.objects.filter(last_login__range=('1970-01-01', '2012-12-31')).values('pk').query
SELECT "auth_user"."id" FROM "auth_user" WHERE "auth_user"."last_login"
BETWEEN 1969-12-31 16:00:00 and 2012-12-30 16:00:00

note that last_login is a DateTimeField which tries to convert string value to datetime.datetime (and I'm in +8 timezone, hence default 00:00:00 becomes 16:00:00 one day before)

On client side, ref How do I output an ISO 8601 formatted string in JavaScript? to generate date string in the format of 'YYYY-mm-dd'.

这篇关于处理日期请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:27