Kelvin
Kelvin

Reputation: 130

Django 'dict' object has no attribute

I am making queries to get the total number of apples by month. Now I want retrieve and print the data of total_apple.

fruits= Fruits.objects\
        .annotate(month = TruncMonth('sold_date'))\
        .values('month')\
        .annotate(total_apple=Sum('apple'))\
        .order_by('-month')

I've tried many ways to print it but returned an error.

I've tried:

1)

total_apple= fruits['total_apple']
print(total_apple)

2)

context['total_apple'] = total_apple
print(context)

An error returned: No exception message supplied

3)

print(fruits.total_apple)

Error returned: 'QuerySet' object has no attribute 'total_apple'

But when I tried print(fruits), it returned queryset that contain the attributes that I want.

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

Upvotes: 1

Views: 12093

Answers (3)

Saad Aleem
Saad Aleem

Reputation: 1745

fruits is a queryset and not a django model instance. Try indexing the fruits queryset like this:

fruits[0].total_apple

UPDATE

Since the accepted answer has .values in it, fruits[0]['total_apple'] will work fine instead of fruits[0].total_apple. values() converts each object in your queryset into a dict.

Upvotes: 4

shafikshaon
shafikshaon

Reputation: 6404

fruits= Fruits.objects\
        .annotate(month = TruncMonth('sold_date'))\
        .values('month')\
        .annotate(total_apple=Sum('apple'))\
        .order_by('-month')

This query returns a list of object. So you can iterate over fruits and print fruit.total_apple

for fruit in fruits:
    print(fruit['total_apple'])

fruits return QueryDict, so you need to access it's value by key like total_apple

below the query.

Also mention that if you want single result you can query like this

fruits= Fruits.objects\
            .annotate(month = TruncMonth('sold_date'))\
            .values('month')\
            .annotate(total_apple=Sum('apple'))\
            .order_by('-month').first()

Then print(fruits.total_apple)

Upvotes: 5

Rarblack
Rarblack

Reputation: 4664

You can always use python shell to test the ideas. This example clearly show the way to get desired output:

>>> 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

In your case, you can do a loop to print all the object's total_apple

for fruit in fruits:
    print(fruit.total_apple)

Example:

>>> users = User.objects.all()
>>> for user in users:
...    print(user.username)
...    
bg
test

Upvotes: 0

Related Questions