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>
不,不,我已經做了平均和一切現在我只想要一個字典,需要每個用戶的ID和得分是這樣的:set = {user_id:score,user_id:score}但是你顯示我的幫助,以及簡化我的工作 –
您計算平均分數的方式效率低下,如果您有1000個用戶,您最終將運行2000個查詢 –
我知道我現在正按照您向我展示的方式進行編輯,您可以用字典幫助我嗎? –