2016-11-16 94 views
0

我在编程初学者,我有一个障碍,所以基本上我要创建这样的如何使用用户标识创建字典?

set = { 
     user_id_1 : 'result_user_id_1', 
     user_id_2 : 'result_user_id_2', 
     user_id_3 : 'result_user_id_3' 
     } 

简体我希望每个用户有它的字典中的得分。

结果来自mytags(teamplatetags),它是所有用户为了获得最终得分而给予彼此分数的分数。

models.py

from django.db import models 
from django.conf import settings 


VALOARE = (
    (1, "Nota 1"), 
    (2, "Nota 2"), 
    (3, "Nota 3"), 
    (4, "Nota 4"), 
    (5, "Nota 5"), 
    (6, "Nota 6"), 
    (7, "Nota 7"), 
    (8, "Nota 8"), 
    (9, "Nota 9"), 
    (10, "Nota 10"), 
) 


class Punctaj(models.Model): 
    acordat_de = models.ForeignKey(settings.AUTH_USER_MODEL, default=0) 
    acordat_catre = models.ForeignKey(settings.AUTH_USER_MODEL, default=0, related_name="acordat_catre") 
    nota = models.PositiveSmallIntegerField(default=0, choices=VALOARE) 

views.py

def home(request): 
    data = dict() 
    data['users']=User.objects.all() 

    if request.method == "POST": 
     for key in request.POST: 
      if 'nota_' in key: 
       nota_acordata = Punctaj.objects.filter(acordat_de=request.user, acordat_catre__id=key.split('_')[1]).first() 
       if nota_acordata: 
        nota_acordata.nota = request.POST.get(key) 
        nota_acordata.save() 

       else: 
        Punctaj.objects.create(acordat_de=request.user, acordat_catre_id=key.split('_')[1], nota=request.POST.get(key)) 
        messages.success(request,"Successfully Voted") 

     return redirect('home') 

    return render(request, "login/home.html", data) 

mytags.py - templatetag

@register.simple_tag 
def results(user): 
    suma = Punctaj.objects.filter(acordat_catre=user).aggregate(punctaj=Sum('nota')).get("punctaj") 
    count = Punctaj.objects.filter(acordat_catre=user).count() 
    if not suma: 
     result = 0 
    else: 
     result = int(suma)/count 
    return result 

模板

<form class ="nota" method="POST" action="">{% csrf_token %} 
    <table class="table table-striped table-bordered"> 
     <thead> 
      <tr> 
       <th> User </th> 
       <th> Nota finala </th> 
      </tr> 
     </thead> 

     <tbody> 
     {% for fotbalist in users %} 
      <tr> 
       <td>{{ fotbalist.username }}</td> 
       <td> 
        <p>{% results fotbalist %}</p> 
       </td> 
      </tr> 
     {% endfor %} 
     </tbody> 
    </table> 
</form> 

回答

2

您正在寻找annotate,看起来像你只是想为每个用户平均“nota”?

User.objects.annotate(score=Avg('acordat_catre__nota')) 

得到的用户列表现在将有一个属性“分数”,一个加此接近,相比模板标签,是它会降低查询的次数,你让相当

你模板是现在

{% for fotbalist in users %} 
     <tr> 
      <td>{{ fotbalist.username }}</td> 
      <td> 
       <p>{{ fotbalist.score }}</p> 
      </td> 
     </tr> 
    {% endfor %} 

如果你真的只是想词典中,你需要做的

dict(User.objects.annotate(score=Avg('acordat_catre__nota')).values_list('id', 'score')) 
+0

不,不,我已经做了平均和一切现在我只想要一个字典,需要每个用户的ID和得分是这样的:set = {user_id:score,user_id:score}但是你显示我的帮助,以及简化我的工作 –

+0

您计算平均分数的方式效率低下,如果您有1000个用户,您最终将运行2000个查询 –

+0

我知道我现在正按照您向我展示的方式进行编辑,您可以用字典帮助我吗? –