这可能是一个非常愚蠢的问题,但是我如何使用下面的查询来检索整数?
staravg = UserReview.objects.filter(name__username__iexact=username).aggregate(Avg('stars'))
如果我在模板中执行 {{ staravg }},我会得到 {'stars__avg': 3.3333333333333335}。我知道我可以使用某种模板过滤器来检索 3.333,但是必须有一种更简单的方法来检索 Integer 对吗? stars 来自 IntegerField 仅供引用。
最佳答案
这是因为 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.
此字典的键是从您聚合的字段自动生成的。
一种选择是从 View 中的字典中获取数字:
staravg = UserReview.objects.filter(name__username__iexact=username).aggregate(Avg('stars'))['stars__avg']
或者,您可以手动设置键名:
staravg = UserReview.objects.filter(name__username__iexact=username).aggregate(stars=Avg('stars'))['stars']
或者,如果您想在模板中获取它,请使用 "dot notation"获取字典项的值:
{{ staravg.stars__avg }}
您可能还需要申请 floatformat
template filter将数字四舍五入到 X 位小数:
{{ staravg.stars__avg|floatformat:3 }}
关于django - 如何在 Django 中检索聚合查询的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27596574/