我是编程的初学者,我遇到了障碍,所以基本上我想创建这样的东西
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>
答案 0 :(得分: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'))