1👍
Updated snippet to take into account possible division by zero error.
It gets the number of objects with average_score
less than specified using __lte queryset filter (Less than or equal to) and divided by the total number of objects in the database.
Everything is done on the database end, and (almost) no data is transferred back and forth, so it should work efficiently even with large number of user objects in the database
queryset = User.objects.all()
total_count = queryset.count()
if total_count:
percentile = float(queryset.filter(average_score__lte=average_score).count())/total_count
else:
return 0.0
1👍
few months ago, i had a similiar problem to find average transactions for this year, such as script below. hopefully can help..
import time
from django import template
from yourapp.models import Transaction
register = template.Library()
now_year = time.strftime("%Y")
@register.simple_tag
def graph_average_income_by_year():
try:
transactions = Transaction.objects.filter(paid=True)\
.filter(payment_date__year=now_year)
count_transactions = transactions.count()
incomes = [ p.total_transfer for p in transactions ]
return ("%.1f" % (float(sum(incomes))/count_transactions) )
except:
return 0.0
Source:stackexchange.com