所以我有这个模型:
class scoreShow(models.Model):
dancer = models.ForeignKey(dancer)
s1 = models.IntegerField(max_length = 2)
s2 = models.IntegerField(max_length = 2)
s3 = models.IntegerField(max_length = 2)
s4 = models.IntegerField(max_length = 2)
s5 = models.IntegerField(max_length = 2)
s6 = models.IntegerField(max_length = 2)
s7 = models.IntegerField(max_length = 2)
counter = models.IntegerField(max_length = 2)
stotal = models.IntegerField(max_length = 3)
field_1 = models.IntegerField(max_length = 20, null=True, blank=True)
field_2 = models.CharField(max_length = 20, null=True, blank=True)
def __unicode__(self):
return str(self.dancer)
从此视图表格中提供信息:
def scores(request):
perf = dancer.objects.filter(perform=True)
if request.method =='POST':
intpk = request.POST.get("form")
whendone = request.POST.get("done")
contestant =dancer.objects.get(pk=intpk)
showcase = inlineformset_factory(dancer, scoreShow, extra = 1)
form = showcase(instance=None)
if whendone == "save":
form = showcase(request.POST, request.FILES, instance=contestant)
if form.is_valid():
form.save()
return render_to_response("scores.html",locals(), context_instance = RequestContext(request))
它接受来自约13个人的1到10的数值。我需要计算13个人投入的平均分数。平均值为2个:
前7个类别的平均值。平均值s1,平均值s2&
所有S的平均值加在一起,因此平均s1总数+ s2总数...除以总条目数。 Ť
如果可能的话,我还想避免让任何人提交两次得分。任何人都可以帮我这个吗?
答案 0 :(得分:1)
您可以通过以下方式使用Aggregation feature:
from django.db.models import Avg
qs = ScoreShow.objects.all()
return qs.aggregate(Avg('s1'), Avg('s2'), Avg('s3'), Avg('s4'), Avg('s5'), Avg('s6'),Avg('s7'))
或更短一些:
qs = ScoreShow.objects.all()
return qs.aggregate(*[Avg('s%d' % i) for i in range(1, 8)])
要计算所有分数的平均值,您需要将汇总与annotate结合使用:
from django.db.models import Avg, Sum
fields = ['s%d' % i for i in range(1,8)]
qs = ScoreShow.objects.annotate(sAll=Sum('id', field='+'.join(fields))).all()
return qs.aggregate(Avg('sAll'))
要确保没有人提交两个分数,请将unique=True
添加到舞者外键:
class ScoreShow(models.Model):
dancer = models.ForeignKey(dancer, unique=True)