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
提交
取消