我正在尝试从Django中非托管数据库查询数据。我正在尝试获取给定日期范围内每小时的对象数量。例如
{'Hour': 18, 'Monday': 235, 'Tuesday': 0, 'Friday': 0, 'Wednesday': 0, 'Thursday': 0, 'Sunday': 163, 'Saturday': 0}
{'Hour': 19, 'Monday': 127, 'Tuesday': 226, 'Friday': 0, 'Wednesday': 0, 'Thursday': 0, 'Sunday': 0, 'Saturday': 0}
该词典表示每天给定小时内的所有对象。问题在于,晚上7点(第19小时)之后,随后的词典中的所有值都应转移一天。例如,在此字典中:
{'Hour': 19, 'Monday': 127, 'Tuesday': 226, 'Friday': 0, 'Wednesday': 0, 'Thursday': 0, 'Sunday': 0, 'Saturday': 0}
星期二值应在星期一条目中,星期一应在星期日条目中,依此类推。
这是我的查询和字典填充代码:
#results filtered by appropriate gender and hour
ordered_query = initial_query.annotate(
Hour=ExtractHour('actualdatetime', tzinfo=eastern),
).values(
'Hour'
).annotate(
Sunday=Coalesce(Sum(Case(When(actualdatetime__week_day=1, then=1)), output_field=IntegerField()), Value(0)),
Monday=Coalesce(Sum(Case(When(actualdatetime__week_day=2, then=1)), output_field=IntegerField()), Value(0)),
Tuesday=Coalesce(Sum(Case(When(actualdatetime__week_day=3, then=1)), output_field=IntegerField()), Value(0)),
Wednesday=Coalesce(Sum(Case(When(actualdatetime__week_day=4, then=1)), output_field=IntegerField()), Value(0)),
Thursday=Coalesce(Sum(Case(When(actualdatetime__week_day=5, then=1)), output_field=IntegerField()), Value(0)),
Friday=Coalesce(Sum(Case(When(actualdatetime__week_day=6, then=1)), output_field=IntegerField()), Value(0)),
Saturday=Coalesce(Sum(Case(When(actualdatetime__week_day=7, then=1)), output_field=IntegerField()), Value(0)),
).values(
'Hour', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
)
#populate list of dictionaries
for item in ordered_query:
tableData[item["Hour"]]["Sunday"] = item["Sunday"]
tableData[item["Hour"]]["Monday"] = item["Monday"]
tableData[item["Hour"]]["Tuesday"] = item["Tuesday"]
tableData[item["Hour"]]["Wednesday"] = item["Wednesday"]
tableData[item["Hour"]]["Thursday"] = item["Thursday"]
tableData[item["Hour"]]["Friday"] = item["Friday"]
tableData[item["Hour"]]["Saturday"] = item["Saturday"]