关于我的django查询,我有一个主要问题。 我的疑问是: -
query=AllTime.objects.values('startdate').order_by('timeid').annotate(spent=Sum('spent')).filter(project_id=project_id,startdate__range=(datetime.datetime.now()-datetime.timedelta(days=15),datetime.datetime.now()))
查询给出了以下输出: -
{
"startdate": "2015-01-12",
"spent": 84
},
{
"startdate": "2015-01-13",
"spent": 7
},
{
"startdate": "2015-01-19",
"spent": 32
}
问题是我得到的是那些已经在我桌子上的日期。 但我想要像这样的输出
{
"startdate": "2015-01-12",
"spent": 84
},
{
"startdate": "2015-01-13",
"spent": 7
},
{
"startdate": "2015-01-14",
"spent": 0
},
{
"startdate": "2015-01-15",
"spent": 0
},
{
"startdate": "2015-01-16",
"spent": 0
},
{
"startdate": "2015-01-17",
"spent": 0
},
{
"startdate": "2015-01-18",
"spent": 0
},
{
"startdate": "2015-01-19",
"spent": 32
}
如何获取django query ???的上述输出
答案 0 :(得分:0)
您无法创建此类查询。唯一的方法是创建一个包含所有必需日期值的列表:
days_to_show = 15
start_date = datetime.date.today() - datetime.timedelta(days=days_to_show)
query = AllTime.objects.values('startdate').order_by('timeid') \
.annotate(spent=Sum('spent')) \
.filter(project_id=project_id,
startdate__range=(start_date, datetime.datetime.now()))
spent_dict = dict((d['startdate'], d['spent']) for d in query)
date_list = [(start_date + datetime.timedelta(days=day)).strftime('%Y-%m-%d')
for day in range(0, days_to_show)]
spent_list = [{'startdate': date, "spent": spent_dict.get(date, 0)}
for date in date_list]