from django.shortcuts import renderfrom django.contrib.auth.decorators import login_requiredfrom django.utils import timezonefrom django.db.models import Sum, Count, Max, When, Case, Value, IntegerFieldfrom django.db.models.functions import TruncDay, TruncMonth, TruncYearimport datetimefrom .models import Profile, Team@login_requireddef profile(request): today = timezone.now() user_profile = Profile.objects.filter(user=request.user).first() expenses = user_profile.expense_set.annotate( field = Case( When(created__year=today.year, then=1), When(created__month=today.month, then=2), When(created__day=today.day, then=3), default=0, output_field=IntegerField() ) ) curent_month_expenses = expenses.filter(created__month=today.month) expenses_per_day = expenses.annotate( day=TruncDay('created')).values('day').annotate( expenses=Count('id'), summary=Sum('amount') ).values('day', 'expenses', 'summary') expenses_per_month = expenses.annotate( month=TruncMonth('created')).values('month').annotate( expenses=Count('id'), summary=Sum('amount') ).values('month', 'expenses', 'summary') expenses_per_year = expenses.annotate( year=TruncYear('created')).values('year').annotate( expenses=Count('id'), summary=Sum('amount') ).values('year', 'expenses', 'summary') print(expenses_per_year[0]) print(expenses_per_year.first()) context = { 'profile': user_profile, 'curent_month_expenses': curent_month_expenses, 'yearly_expenses': expenses_per_year, 'dayly_expenses': expenses_per_day, 'monthly_expenses': expenses_per_month, } return render(request, 'accounts/profile.html', context)為什么打印語句中的輸出不同?輸出:
1 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
與普遍的看法相反,并不等同于.如果不存在排序,則將按主鍵排序,如 .first()
上的文檔中所述:qs.first()
qs[0]
qs.first()
返回與查詢集匹配的第一個對象,或者如果沒有匹配的對象。如果未定義排序,則查詢集按主鍵自動排序。這可能會影響聚合結果,如與默認排序的交互或
order_by()中所述
。None
QuerySet
如果按主鍵排序,它將因此還原 .您可以通過包含自己來解決此問題:GROUP BY
.order_by
expenses_per_year = expenses.values(
year=TruncYear('created')
).annotate(
expenses=Count('id'), summary=Sum('amount')
).order_by('year')
此外,您還可以在 部件中添加注釋,并且不需要在 中再次包含注釋。這使查詢更具可讀性。year=TruncYear('created').values(..).values(..)
添加回答
舉報
0/150
提交
取消