日期運算參考


# 實際練習

# 查出都是八月的收入

多 filter

accounts = Account.objects.filter(date__month=8).filter(io='INPUT') #但這邊有個問題,不管哪年八月都會被查到吧?

# 查出 12 個月內的記帳並各個月分加總

構思

data = {}
        now = datetime.datetime.now()
        # 收集今年月份
        today_year = now.year
        today_year_months = range(1,now.month+1)
        for today_year_month in today_year_months:
            month_key = '%s_%s' % (today_year, today_year_month)
            data[month_key]=[] # 建立每個月份的 list
            accounts = Account.objects.filter(date__year=today_year).filter(date__month=today_year_month).filter(io='INPUT')
            for node in accounts:
                data[month_key].append(node.price)
            # 加總
            data[month_key] = sum(data[month_key])
        # 如果 data 沒有 12 個 key len (data.keys ());會做這樣的判斷 因為想減少 DB 連線次數 雖然只有年底會節省到 -.-
        if len(data.keys()) < 12:
            # 繼續收集去年月份
            last_year =  int(now.year) -1
            last_year_months = range(now.month+1, 13)
            for last_year_month in last_year_months:
                month_key = '%s_%s' % (last_year, last_year_month)
                data[month_key]=[] # 建立每個月份的 list
                accounts = Account.objects.filter(date__year=last_year).filter(date__month=last_year_month).filter(io='INPUT')
                for node in accounts:
                    data[month_key].append(node.price)
                # 加總
                data[month_key] = sum(data[month_key])

其實 key 不要這麼懶應該是能做補 0 處理的
有想到去判斷月份,如果有到十位數就不用補零,反之要補,我們就會得到 202309、202310 的 key

參考資料:

  • 獲取當前月份
  • 跨越年份的 12 個月
  • 格式化字串