我的建議是你添加一個字段到你的模型中,因爲它不可能在.values_list
中使用__month
。在註解之前,可以使用Values_list對查詢進行分組。
字段可能類似。
year_month = models.CharField(index=True)
你可以改寫你的模型的保存方法和做類似
def save(self, *args, **kwargs)
# Not sure if auto_add_now already set the value, could use timezone.now()
if not self.id: # thus not saved yet
self.year_month = self.created_at.strftime("%Y%m")
super(Model, self).save(*args, **kwargs)
現在它可以註釋你的價格。
Project.objects.values_list('year_month').annotate(price_sum=Sum("price_aux"))
如果您需要更多信息,我相信您可以擴大values_list。
Project.objects.values_list('year_month').annotate(price_sum=Sum("price_aux")) \
.values_list('name', 'year_month', 'price_sum')
在沒有添加字段的情況下這樣做是可能的。假設你想過去的一年。
import datetime
from django.utils import timezone
def my_list_view(request):
end = timezone.now()
# note, could do some weird stuff in years with 366 days
begin = (end - datetime.timedelta(days=365)).replace(day=1)
container = {}
while begin < end:
container[begin.strftime("%Y%m")] = 0
begin = (begin + datetime.timedelta(weeks=5).replace(day=1)
for project in Project.objects.iterator():
container[project.created_at.strftime("%Y%m")] += price
# Now you can render your template
檢索每月的價格你爲什麼不使用一個表有兩列,一爲一個月,一個價格。然後您可以簡單地按月選擇價格。 –
我正在使用類似的東西,但我很難從數據庫提取飛蛾,可以做一個小例子? – PetarP
假設你的模型被稱爲'價格',並且有兩個字段'month'和'price',那麼你可以做'ppm = Price.objects.filter(month = 1)[0]'。 'ppm.price'然後給你實際價格。 –