i'm a rookie in programming and i ran into a problem in django.
So i'm trying to sort a dictionary based on the value. I've tryed several methods seen here, but thing is nothing works for me. It worked to make the dictionary but i don't know why it's not sorting.
So 'scoruri' is the dictionary: when using it in html it's showing like this {User: alex_py: 6, User: ion: 3, User: lil: 1, User: sss: 1, User: ddd: 1, User: bbb: 7}, 'result' is the score for each 'user'(key). When i'm printing the type of scoruri it prints 6 times (type 'dict')
It may be possible that each key:value in scoruri to be actually a dictionary so i'm having a dictionary of dictionaries?
Below are the methods i've tryed to sort.
views.py
def home(request):
data = dict()
data['users'] = User.objects.all()
data['scoruri'] = dict()
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')
for user in data['users']:
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
data['scoruri'][user] = result
# sorted(data['scoruri'].items())
# rezultate = sorted(data['scoruri'].items(), key=operator.itemgetter(1))
print(type(data['scoruri']))
return render(request, "login/home.html", data)
template
{{ scoruri }}
<!--{{ rezultate }}-->
<!--{% for key, value in scoruri %}-->
<!--{{ key }}:{{ value }}-->
<!--{% endfor %}-->