gpt4 book ai didi

python - Django 查询日期时间

转载 作者:行者123 更新时间:2023-11-29 23:10:45 26 4
gpt4 key购买 nike

我的 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 查询的上述输出???

最佳答案

您无法创建此类查询。唯一的方法是创建一个包含所有所需日期的值的列表:

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]

关于python - Django 查询日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28085354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com