亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么此輸出不同?

為什么此輸出不同?

神不在的星期二 2022-09-20 15:57:56
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()中所述。NoneQuerySet

如果按主鍵排序,它將因此還原 .您可以通過包含自己來解決此問題: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(..)


查看完整回答
反對 回復 2022-09-20
  • 1 回答
  • 0 關注
  • 100 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號