在 Python 3 中:
dict_values
您可以通过将其转换为 a来解决它list
:
total_paid = list(Payment.objects.aggregate(Sum('amount')).values())[0] or 0 # the or 0 is required in case the query is an empty query set.
前面的代码避免使用'column_name__sum'
as 键,但如果您更喜欢字典方式:
total_paid = Payment.objects.aggregate(Sum('amount'))['amount__sum'] or 0
在效率方面,我用我有的一些数据做了一个测试,似乎使用字典键更快:
In [9]: %timeit total = Pledge.objects.filter(user=user, group__isnull=True).aggregate(Sum('amount'))['amount__sum'] or 0
3.13 ms ± 25.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [10]: %timeit total = list(Pledge.objects.filter(user=user, group__isnull=True).aggregate(Sum('amount')).values())[0] or 0
3.22 ms ± 61.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
在可读性方面,我认为@mehmet 的解决方案是最好的,我也测试了它的效率:
In [18]: %timeit Pledge.objects.filter(user=user, group__isnull=True).aggregate(sum=Sum('amount'))['sum'] or 0
3.22 ms ± 124 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)