猿问

Django'dict'对象没有属性

我正在查询以获取每月的苹果总数。现在我想检索和打印total_apple.


fruits= Fruits.objects\

        .annotate(month = TruncMonth('sold_date'))\

        .values('month')\

        .annotate(total_apple=Sum('apple'))\

        .order_by('-month')

我尝试了很多方法来打印它,但返回了一个错误。


我试过了:


1)


total_apple= fruits['total_apple']

print(total_apple)

2)


context['total_apple'] = total_apple

print(context)

返回错误: No exception message supplied


3)


print(fruits.total_apple)

错误返回: 'QuerySet' object has no attribute 'total_apple'


但是当我尝试时print(fruits),它返回了包含我想要的属性的查询集。


<QuerySet [{'month': datetime.date(2018, 10, 1), 'total_apple': 1636}, {'month': datetime.date(2018, 9, 1), 'total_apple': 1658},.....>


元芳怎么了
浏览 250回答 3
3回答

温温酱

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

qq_遁去的一_1

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

偶然的你

你总是可以使用 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_applefor fruit in fruits:&nbsp; &nbsp; print(fruit.total_apple)例子:>>> users = User.objects.all()>>> for user in users:...&nbsp; &nbsp; print(user.username)...&nbsp; &nbsp;&nbsp;bgtest
随时随地看视频慕课网APP

相关分类

Python
我要回答