为什么此输出不同?

from django.shortcuts import render

from django.contrib.auth.decorators import login_required

from django.utils import timezone

from django.db.models import Sum, Count, Max, When, Case, Value, IntegerField

from django.db.models.functions import TruncDay, TruncMonth, TruncYear

import datetime


from .models import Profile, Team


@login_required

def 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)

为什么打印语句中的输出不同?输出:



神不在的星期二
浏览 86回答 1
1回答

扬帆大鱼

与普遍的看法相反,并不等同于.如果不存在排序,则将按主键排序,如 .first() 上的文档中所述:qs.first()qs[0]qs.first()返回与查询集匹配的第一个对象,或者如果没有匹配的对象。如果未定义排序,则查询集按主键自动排序。这可能会影响聚合结果,如与默认排序的交互或order_by()中所述。NoneQuerySet如果按主键排序,它将因此还原 .您可以通过包含自己来解决此问题:GROUP BY.order_byexpenses_per_year = expenses.values(    year=TruncYear('created')).annotate(    expenses=Count('id'), summary=Sum('amount')).order_by('year')此外,您还可以在 部件中添加注释,并且不需要在 中再次包含注释。这使查询更具可读性。year=TruncYear('created').values(..).values(..)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python