Jason G
Jason G

Reputation: 200

How do I get the value of an dictionary for Django?

I am using aggregate to average out some values in a table. It returns as: enter image description here

How would I display 3.5 in the template? I am passing rating as a dictionary to the template.

Upvotes: 0

Views: 109

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477883

You can subscript, so:

rating['review_content__rating__avg']

It might however make sense to pass the expression in the .aggregate(…) [Django-doc] call to make the key shorter, and also make it more robust for fieldname changes: in that case you only need to change the expression.

For example:

from django.db.models import Avg

result = MyModel.objects.aggregate(
    avg_review=Avg('review_content__rating')
)['avg_review']  # 3.5

Here we thus give the aggregate the name avg_review. For more complex aggregates, it is even mandatory to give a name yourself.

Upvotes: 1

Related Questions