2014-06-18 92 views
2

所以我有這個模型:如何計算django中這些條目的平均分數?

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平均值:

  1. 7個類別的平均值。 s1的平均值,s2的平均值&

  2. 將所有S的平均值加起來得到平均值s1總計+ s2總數......除以總條目數。 T

我也想避免讓任何人提交兩次分數,如果可能的話。誰能幫我這個?

回答

1
  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)]) 
    
  2. 計算所有分數相加起來,你需要骨料與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')) 
    
  3. 爲了確保沒有人提交兩個分數加unique=True到舞蹈演員外鍵:

    class ScoreShow(models.Model): 
        dancer = models.ForeignKey(dancer, unique=True) 
    
+0

哇感謝,第一部分工作正常,但是,對於我不斷收到此錯誤的總平均:和」對象有沒有屬性'全部',我嘗試過濾器,我也有這個錯誤,以及任何想法?並再次感謝你 – user3525985

+0

我的錯誤,我忘了一個右括號。 – daniula

+0

完美的作品!,非常感謝 – user3525985