3 回答

TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
fruits
是一個(gè)查詢集而不是 django 模型實(shí)例。嘗試fruits
像這樣索引查詢集:
fruits[0].total_apple
更新
由于接受的答案包含.values
在其中,因此fruits[0]['total_apple']
可以正常工作而不是fruits[0].total_apple
. values()
將查詢集中的每個(gè)對(duì)象轉(zhuǎn)換為dict
.

TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
fruits= Fruits.objects\
.annotate(month = TruncMonth('sold_date'))\
.values('month')\
.annotate(total_apple=Sum('apple'))\
.order_by('-month')
此查詢返回對(duì)象列表。所以你可以迭代fruits并打印fruit.total_apple
for fruit in fruits:
print(fruit['total_apple'])
fruits 返回QueryDict,因此您需要通過鍵訪問它的值,例如 total_apple
在查詢下方。
還要提到,如果你想要單個(gè)結(jié)果,你可以這樣查詢
fruits= Fruits.objects\
.annotate(month = TruncMonth('sold_date'))\
.values('month')\
.annotate(total_apple=Sum('apple'))\
.order_by('-month').first()
然后 print(fruits.total_apple)

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
你總是可以使用 python shell 來測(cè)試這些想法。此示例清楚地顯示了獲得所需輸出的方法:
>>> 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
在您的情況下,您可以循環(huán)打印所有對(duì)象的 total_apple
for fruit in fruits:
print(fruit.total_apple)
例子:
>>> users = User.objects.all()
>>> for user in users:
... print(user.username)
...
bg
test
添加回答
舉報(bào)