This might be a really dumb question, but how do I just retrieve the Integer using the query below?
staravg = UserReview.objects.filter(name__username__iexact=username).aggregate(Avg('stars'))
If I do {{ staravg }} in my template, I get {'stars__avg': 3.3333333333333335}. I am aware I could just retrieve the 3.333 with a template filter of some sort, but there has to be a more simple way to just retrieve the Integer right? stars is from an IntegerField FYI.
This is because aggregate()
returns a dictionary:
aggregate() is a terminal clause for a QuerySet that, when invoked, returns a dictionary of name-value pairs. The name is an identifier for the aggregate value; the value is the computed aggregate. The name is automatically generated from the name of the field and the aggregate function.
The key of this dictionary is automatically generated from the field(s) you aggregate by.
One option would be to get the number from the dictionary in the view:
staravg = UserReview.objects.filter(name__username__iexact=username).aggregate(Avg('stars'))['stars__avg']
Or, you can set the key name manually:
staravg = UserReview.objects.filter(name__username__iexact=username).aggregate(stars=Avg('stars'))['stars']
Or, if you want to get it in the template, use a "dot notation" to get the value of a dictionary item:
{{ staravg.stars__avg }}
You may also need to apply floatformat
template filter to round a number to the X decimal places:
{{ staravg.stars__avg|floatformat:3 }}