第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Django'dict'對(duì)象沒有屬性

Django'dict'對(duì)象沒有屬性

元芳怎么了 2021-09-25 13:20:45
我正在查詢以獲取每月的蘋果總數(shù)?,F(xiàn)在我想檢索和打印total_apple.fruits= Fruits.objects\        .annotate(month = TruncMonth('sold_date'))\        .values('month')\        .annotate(total_apple=Sum('apple'))\        .order_by('-month')我嘗試了很多方法來打印它,但返回了一個(gè)錯(cuò)誤。我試過了:1)total_apple= fruits['total_apple']print(total_apple)2)context['total_apple'] = total_appleprint(context)返回錯(cuò)誤: No exception message supplied3)print(fruits.total_apple)錯(cuò)誤返回: 'QuerySet' object has no attribute 'total_apple'但是當(dāng)我嘗試時(shí)print(fruits),它返回了包含我想要的屬性的查詢集。<QuerySet [{'month': datetime.date(2018, 10, 1), 'total_apple': 1636}, {'month': datetime.date(2018, 9, 1), 'total_apple': 1658},.....>
查看完整描述

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_applevalues()將查詢集中的每個(gè)對(duì)象轉(zhuǎn)換為dict.


查看完整回答
反對(duì) 回復(fù) 2021-09-25
?
qq_遁去的一_1

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)


查看完整回答
反對(duì) 回復(fù) 2021-09-25
?
偶然的你

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


查看完整回答
反對(duì) 回復(fù) 2021-09-25
  • 3 回答
  • 0 關(guān)注
  • 264 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)