3 回答

TA贡献1752条经验 获得超4个赞
fruits
是一个查询集而不是 django 模型实例。尝试fruits
像这样索引查询集:
fruits[0].total_apple
更新
由于接受的答案包含.values
在其中,因此fruits[0]['total_apple']
可以正常工作而不是fruits[0].total_apple
. values()
将查询集中的每个对象转换为dict
.

TA贡献1725条经验 获得超7个赞
fruits= Fruits.objects\
.annotate(month = TruncMonth('sold_date'))\
.values('month')\
.annotate(total_apple=Sum('apple'))\
.order_by('-month')
此查询返回对象列表。所以你可以迭代fruits并打印fruit.total_apple
for fruit in fruits:
print(fruit['total_apple'])
fruits 返回QueryDict,因此您需要通过键访问它的值,例如 total_apple
在查询下方。
还要提到,如果你想要单个结果,你可以这样查询
fruits= Fruits.objects\
.annotate(month = TruncMonth('sold_date'))\
.values('month')\
.annotate(total_apple=Sum('apple'))\
.order_by('-month').first()
然后 print(fruits.total_apple)

TA贡献1841条经验 获得超3个赞
你总是可以使用 python shell 来测试这些想法。此示例清楚地显示了获得所需输出的方法:
>>> from django.contrib.auth.models import User
>>> user = User.objects.all()
>>> user
<QuerySet [<User: bg>, <User: test>]>
>>> user.all()
<QuerySet [<User: bg>, <User: test>]>
>>> user[0]
<User: bg>
>>> user[1].username #this is the way to get theyou need to do
'test'
>>> user[1].password
'pbkdf2_sha256$100000$nJzzPRnFyNvq$MUmPTnzCKJRqxHskU5OpUtFIgMwY5Ap8fPMQMm4fUFQ
在您的情况下,您可以循环打印所有对象的 total_apple
for fruit in fruits:
print(fruit.total_apple)
例子:
>>> users = User.objects.all()
>>> for user in users:
... print(user.username)
...
bg
test
添加回答
举报